英文:
Go Template : Use nested struct's field and {{range}} tag together
问题
我有以下嵌套结构体,我想在模板中使用{{range .Foos}}
标签来迭代它们。
type Foo struct {
Field1, Field2 string
}
type NestedStruct struct {
NestedStructID string
Foos []Foo
}
我尝试使用以下html/template
,但它无法访问NestedStruct
中的NestedStructID
。
{{range .Foos}} { source: '{{.Field1}}', target: '{{.NestedStructID}}' }{{end}}
在golang模板中有没有办法实现我想要的效果?
英文:
I have the following nested struct and I would like to iterate them in a template, in a {{range .Foos}}
tag.
type Foo struct {
Field1, Field2 string
}
type NestedStruct struct {
NestedStructID string
Foos []Foo
}
I'm trying with the following html/template but it can't access the NestedStructID
from NestedStruct
.
{{range .Foos}} { source: '{{.Field1}}', target: '{{.NestedStructID}}' }{{end}}
Is there any way with golang templates to do what I'd like to do?
答案1
得分: 3
你不能像那样访问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的初始值。
英文:
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.
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
.
For example:
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}}`
Output (try it on the Go Playground):
{ source: 'f1-1', target: 'nsid' }
{ source: 'f1-2', target: 'nsid' }
<nil>
This is documented in text/template
:
> When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论