Range index by array in templates
I understand that you can use an index within a range:
{{range $i, $e := .First}}$e - {{index $.Second $i}}{{end}}
From: how to use index within a range in html / template to iterate through parallel arrays?
How can I change the range by 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}}
+3
source to share
1 answer
You can use a nested loop just like you would if you were writing code.
Shown here is code demonstrating what's also available in 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)
}
+7
source to share