Reputation: 3898
I am trying to range over a couple of nested slices inside a template but get an error:
panic: template: abc:3: unexpected <range> in range
goroutine 1 [running]:
text/template.Must(...)
/usr/local/go/src/text/template/helper.go:23
main.main()
/tmp/sandbox748332064/main.go:38 +0x560
I've tried searching the docs but can't seem to figure out a workaround to being able to execute the code, even though is seems really simple.
My code:
package main
import (
"log"
"os"
"text/template"
)
type Person struct {
name string
children []string
}
func main() {
p := []*Person{
{
name: "Susy",
children: []string{"Bob", "Herman", "Sherman"},
},
{
name: "Norman",
children: []string{"Rachel", "Ross", "Chandler"},
},
}
str := `
{{$people := .}}
{{range $i, $pp := range $people}}
{{$children := $pp.children}}
Name: {{$pp.name}}
Children:
{{range $j, $c := $children}}
Child {{$j}}: {{$c}}
{{end}}
{{end}}
`
t := template.Must(template.New("abc").Parse(str))
err := t.Execute(os.Stdout, p)
if err != nil {
log.Println(err)
}
}
Upvotes: 0
Views: 246
Reputation: 120941
Use this syntax for range:
{{range $i, $pp := $people}}
{{$children := $pp.Children}}
Name: {{$pp.Name}}
Children:
{{range $j, $c := $children}}
Child {{$j}}: {{$c}}
{{end}}
{{end}}
Also, export the struct fields so the fields can be used by the template. Use those exported names in the template.
Upvotes: 4