I understand you can use index inside range:
{{range $i, $e := .First}}$e - {{index $.Second $i}}{{end}}
From: how to use index inside range in html/template to iterate through parallel arrays?
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}}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With