英文:
Concrete range example
问题
Go文档中关于text/template包的说明非常抽象,以至于我很难弄清楚如何遍历一个对象的切片。以下是我目前的尝试(对我来说没有输出):
package main
import (
"os"
"text/template"
)
type Context struct {
people []Person
}
type Person struct {
Name string // 以大写字母开头的字段是可导出的
Senior bool
}
func main() {
// Range示例
tRange := template.New("Range Example")
ctx2 := Context{people: []Person{Person{Name: "Mary", Senior: false}, Person{Name: "Joseph", Senior: true}}}
tRange = template.Must(
tRange.Parse(`
{{range $i, $x := $.people}} Name={{$x.Name}} Senior={{$x.Senior}} {{end}}
`))
tRange.Execute(os.Stdout, ctx2)
}
英文:
The Go documentation on the text/template package is so abstract that I'm having trouble figuring out how to actually range over a slice of objects. Here's my attempt so far (This outputs nothing for me):
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)
}
答案1
得分: 5
范围是正确的。问题在于Context结构体中的People字段没有被导出。模板包会忽略未导出的字段。将类型定义更改为:
type Context struct {
People []Person // 注意,People以大写字母P开头。
}
将模板更改为:
{{range $i, $x := $.People}} Name={{$x.Name}} Senior={{$x.Senior}} {{end}}
英文:
The range is correct. The problem is that the Context people field is not exported. The template package ignores unexported fields. Change the type definition to:
type Context struct {
People []Person // <-- note that People starts with capital P.
}
and the template to:
{{range $i, $x := $.People}} Name={{$x.Name}} Senior={{$x.Senior}} {{end}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论