具体范围示例

huangapple go评论89阅读模式
英文:

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}}

playground

英文:

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}}

playground

huangapple
  • 本文由 发表于 2014年12月15日 07:07:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/27475193.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定