我知道你可以使用范围内的索引:
{{range $i, $e := .First}}$e - {{index $.Second $i}}{{end}}
Run Code Online (Sandbox Code Playgroud)
来自:如何在html/template中使用index范围来迭代并行数组?
如果索引还包含数组,我如何对索引进行范围调整?
例如.
type a struct {
Title []string
Article [][]string
}
IndexTmpl.ExecuteTemplate(w, "index.html", a)
Run Code Online (Sandbox Code Playgroud)
的index.html
{{range $i, $a := .Title}}
{{index $.Article $i}} // Want to range over this.
{{end}}
Run Code Online (Sandbox Code Playgroud)
Pau*_*kin 17
您可以使用嵌套循环,就像编写代码一样.
这里有一些代码证明了这一点,也可以在操场上找到.
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)
}
Run Code Online (Sandbox Code Playgroud)