具体范围示例

问题描述 投票:5回答:1

关于文本/模板包的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)
}
templates go go-templates
1个回答
5
投票

范围是正确的。问题是Context people字段不是exported。模板包忽略未导出的字段。将类型定义更改为:

type Context struct {
   People []Person // <-- note that People starts with capital P.
}

和模板:

 {{range $i, $x := $.People}} Name={{$x.Name}} Senior={{$x.Senior}}  {{end}}

playground

© www.soinside.com 2019 - 2024. All rights reserved.