我试图遍历模板中的几个嵌套切片,但出现错误:
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
我试过搜索文档,但似乎无法找到能够执行代码的解决方法,尽管这看起来非常简单。
我的代码:
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)
}
}
MMMHUHU
相关分类