英文:
Print the current index of a slice when iterating using the html/template package
问题
我尝试使用html/template包和Revel框架进行迭代时,打印切片的当前索引,但是我没有得到预期的结果。
我的操作如下:
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
,而是DevMode RunMode currentLocale errors flash test_slice session title
。
我做错了什么?
英文:
I try to print the current index of a slice when iterating using the html/template package with Revel but I don't get the expected result.
My action:
func (c App) Index() revel.Result {
test_slice := []string{"t", "e", "s", "t"}
return c.Render(test_slice)
}
My template:
{{range $i, $test_slice := .}}
{{$i}}
{{end}}
Instead of getting 0 1 2 3
,
I get DevMode RunMode currentLocale errors flash test_slice session title
What did I do wrong ?
答案1
得分: 2
我担心你没有遍历test_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)
}
}
输出:
0
1
2
3
你的代码实际上是在遍历一个map,其中test_slice
只是其中一个值。你看到的是这个map的键名,其中test_slice
是其中之一。要使其正常工作,你应该将模板更改为:
{{range $i, $test_slice := .test_slice}}
{{$i}}
{{end}}
可以参考这个Playground示例:http://play.golang.org/p/are5JNPXt1
英文:
I am afraid you are not iterating over the test_slice
array. If you did, your code would look something like this:
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)
}
}
Output:
0
1
2
3
Your code is rather iterating over a map where test_slice
is just one of the values. What you see is the key names of this map, where test_slice
is one of them. To make it work, you should change your template to:
{{range $i, $test_slice := .test_slice}}
{{$i}}
{{end}}
Consider this Playground example: http://play.golang.org/p/are5JNPXt1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论