英文:
Range over array index in templates
问题
我了解你可以在range内部使用index:
{{range $i, $e := .First}}$e - {{index $.Second $i}}{{end}}
来源:https://stackoverflow.com/questions/16141467/how-to-use-index-inside-range-in-html-template-to-iterate-through-parallel-array
如果索引也包含一个数组,我该如何遍历索引?
例如:
type a struct {
Title []string
Article [][]string
}
IndexTmpl.ExecuteTemplate(w, "index.html", a)
index.html
{{range $i, $a := .Title}}
{{index $.Article $i}} // 想要遍历这个数组。
{{end}}
英文:
I understand you can use index inside range:
{{range $i, $e := .First}}$e - {{index $.Second $i}}{{end}}
How do I range over the index if it also contains an array?
Eg.
type a struct {
Title []string
Article [][]string
}
IndexTmpl.ExecuteTemplate(w, "index.html", a)
index.html
{{range $i, $a := .Title}}
{{index $.Article $i}} // Want to range over this.
{{end}}
答案1
得分: 37
你可以使用嵌套循环,就像编写代码一样。
这是一些演示代码,也可以在 playground 上找到。
package main
import (
"html/template"
"os"
)
type a struct {
Title []string
Article [][]string
}
var data = &a{
Title: []string{"One", "Two", "Three"},
Article: [][]string{
[]string{"a", "b", "c"},
[]string{"d", "e"},
[]string{"f", "g", "h", "i"}},
}
var tmplSrc = `
{{range $i, $a := .Title}}
Title: {{$a}}
{{range $article := index $.Article $i}}
Article: {{$article}}.
{{end}}
{{end}}`
func main() {
tmpl := template.Must(template.New("test").Parse(tmplSrc))
tmpl.Execute(os.Stdout, data)
}
英文:
You can use a nested loop, just as you would if you were writing code.
Here's some code demonstrating that, also available on the playground.
package main
import (
"html/template"
"os"
)
type a struct {
Title []string
Article [][]string
}
var data = &a{
Title: []string{"One", "Two", "Three"},
Article: [][]string{
[]string{"a", "b", "c"},
[]string{"d", "e"},
[]string{"f", "g", "h", "i"}},
}
var tmplSrc = `
{{range $i, $a := .Title}}
Title: {{$a}}
{{range $article := index $.Article $i}}
Article: {{$article}}.
{{end}}
{{end}}`
func main() {
tmpl := template.Must(template.New("test").Parse(tmplSrc))
tmpl.Execute(os.Stdout, data)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论