猿问

具体范围示例

关于 text/template 包的 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)

}


眼眸繁星
浏览 183回答 1
1回答

慕村9548890

范围是正确的。问题是未导出Context people 字段。模板包忽略未导出的字段。将类型定义更改为:type&nbsp;Context&nbsp;struct&nbsp;{ &nbsp;&nbsp;&nbsp;People&nbsp;[]Person&nbsp;//&nbsp;<--&nbsp;note&nbsp;that&nbsp;People&nbsp;starts&nbsp;with&nbsp;capital&nbsp;P. &nbsp;&nbsp;&nbsp;}和模板:&nbsp;{{range&nbsp;$i,&nbsp;$x&nbsp;:=&nbsp;$.People}}&nbsp;Name={{$x.Name}}&nbsp;Senior={{$x.Senior}}&nbsp;&nbsp;{{end}}
随时随地看视频慕课网APP

相关分类

Go
我要回答