更新时间:2022-11-22 11:28:12
您无法像这样到达NestedStructID
字段,因为{{range}}
操作将每次迭代中的管线(点.
)设置为当前元素.
You can't reach the NestedStructID
field like that because the {{range}}
action sets the pipeline (the dot .
) in each iteration to the current element.
您可以使用$
,该参数设置为传递给Template.Execute()
的数据参数;因此,如果您传递值NestedStruct
,则可以使用$.NestedStructID
.
You may use the $
which is set to the data argument passed to Template.Execute()
; so if you pass a value of NestedStruct
, you can use $.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}}`
输出(在游乐场上尝试):
{ source: 'f1-1', target: 'nsid' }
{ source: 'f1-2', target: 'nsid' }
<nil>
此文档记录在 text/template
:
This is documented in text/template
:
执行开始时,将$设置为传递给Execute的data参数,即dot的起始值.
When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.