Go 使用html/模板包进行迭代时,打印切片的当前索引
当使用带有Revel的html/template包进行迭代时,我尝试打印切片的当前索引,但没有得到预期的结果 我的行动:Go 使用html/模板包进行迭代时,打印切片的当前索引,go,revel,Go,Revel,当使用带有Revel的html/template包进行迭代时,我尝试打印切片的当前索引,但没有得到预期的结果 我的行动: func (c App) Index() revel.Result { test_slice := []string{"t", "e", "s", "t"} return c.Render(test_slice) } {{range $i, $test_slice := .}} {{$i}} {{end}} 0 1 2
func (c App) Index() revel.Result {
test_slice := []string{"t", "e", "s", "t"}
return c.Render(test_slice)
}
{{range $i, $test_slice := .}}
{{$i}}
{{end}}
0
1
2
3
我的模板:
func (c App) Index() revel.Result {
test_slice := []string{"t", "e", "s", "t"}
return c.Render(test_slice)
}
{{range $i, $test_slice := .}}
{{$i}}
{{end}}
0
1
2
3
而不是获得0 1 2 3
我得到DevMode运行模式currentLocale错误flash test\u slice会话标题
我做错了什么?恐怕您没有在
测试片
数组上迭代。如果您这样做了,您的代码将如下所示:
package main
import (
"os"
"html/template"
)
const templateString = `{{range $i, $test_slice := .}}
{{$i}}
{{end}}`
func main() {
t, err := template.New("foo").Parse(templateString)
if err != nil {
panic(err)
}
test_slice := []string{"t", "e", "s", "t"}
err = t.Execute(os.Stdout, test_slice)
if err != nil {
panic(err)
}
}
输出:
func (c App) Index() revel.Result {
test_slice := []string{"t", "e", "s", "t"}
return c.Render(test_slice)
}
{{range $i, $test_slice := .}}
{{$i}}
{{end}}
0
1
2
3
您的代码相当于在映射上迭代,test\u slice
只是其中一个值。您看到的是此地图的关键名称,test\u slice
是其中之一。要使其正常工作,您应将模板更改为:
{{range $i, $test_slice := .test_slice}}
{{$i}}
{{end}}
以这个操场为例:谢谢,这很有道理!