文本/模板包上的Go文档是如此抽象,以至于我很难弄清楚如何在对象的切片上进行实际的范围。到目前为止,我的尝试是这样的(这对我来说没有结果):
package main
import (
"os"
templ "text/template"
)
type Context struct {
people []Person
}
type Person struct {
Name string //exported field since it begins with a capital letter
Senior bool
}
func main() {
// Range example
tRange := templ.New("Range Example")
ctx2 := Context{people: []Person{Person{Name: "Mary", Senior: false}, Person{Name: "Joseph", Senior: true}}}
tRange = templ.Must(
tRange.Parse(`
{{range $i, $x := $.people}} Name={{$x.Name}} Senior={{$x.Senior}} {{end}}
`))
tRange.Execute(os.Stdout, ctx2)
}发布于 2014-12-14 23:14:50
范围是正确的。问题是Context people字段不是出口。模板包忽略未导出的字段。将类型定义更改为:
type Context struct {
People []Person // <-- note that People starts with capital P.
}以及模板:
{{range $i, $x := $.People}} Name={{$x.Name}} Senior={{$x.Senior}} {{end}}游乐场
https://stackoverflow.com/questions/27475193
复制相似问题