我有以下嵌套结构,我想在{{range .Foos}}
标记的模板中迭代它们。
type Foo struct {
Field1, Field2 string
}
type NestedStruct struct {
NestedStructID string
Foos []Foo
}
我正在尝试使用以下html /模板,但无法从NestedStructID
访问NestedStruct
。
{{range .Foos}} { source: '{{.Field1}}', target: '{{.NestedStructID}}' }{{end}}
golang模板有什么方法可以做我想做的事情吗?
答案 0 :(得分:2)
您无法像这样到达NestedStructID
字段,因为{{range}}
操作会在每次迭代中将管道(点.
)设置为当前元素。
您可以使用$
设置为传递给Template.Execute()
的数据参数;因此,如果您传递的值为NestedStruct
,则可以使用$.NestedStructID
。
例如:
func main() {
t := template.Must(template.New("").Parse(x))
ns := NestedStruct{
NestedStructID: "nsid",
Foos: []Foo{
{"f1-1", "f2-1"},
{"f1-2", "f2-2"},
},
}
fmt.Println(t.Execute(os.Stdout, ns))
}
const x = `{{range .Foos}}{ source: '{{.Field1}}', target: '{{$.NestedStructID}}' }
{{end}}`
输出(在Go Playground上尝试):
{ source: 'f1-1', target: 'nsid' }
{ source: 'f1-2', target: 'nsid' }
<nil>
text/template
中记录了这一点:
执行开始时,$设置为传递给Execute的数据参数,即dot的起始值。