英文:
Calling subtemplates from within a loop in Go template
问题
当我在{{ range }}
循环之外导入一个子模板时,变量可以成功传递到导入的模板中:
...
{{ template "userdata" . }}
...
(在这里,我可以在内部模板userdata
中访问外部模板的变量)。到目前为止都很好。
然而,当在{{ range }}
循环内部调用相同方式的导入时,它不起作用:
...
{{ range $instance := .Instances }}
- type: instance
metadata:
userdata: {{ template "userdata" . }}
...
上述代码会报错,错误信息类似于:
Error: template: template.tmpl:3:46: 执行"userdata"时出错,无法在类型int中评估字段XXX`
据我理解,它会用循环迭代变量遮蔽我的上下文变量,所以它不起作用。
我应该如何正确地做这件事?
当在range
循环内部时,我如何将.
的值传递到模板"userdata"之外?
英文:
When I am importing a subtemplate outside of a {{ range }}
loop, variables are passed successfully inside the imported template:
...
{{ template "userdata" . }}
...
(here, I can access my outer templates variables in the inner template userdata
). So far so good.
However same fashion import doesn't work when being called inside a {{ range }}
loop:
...
{{ range $instance := .Instances }}
- type: instance
metadata:
userdata: {{ template "userdata" . }}
...
Above ends with error messaging out something like:
Error: template: template.tmpl:3:46: executing "userdata" at <XXX>: can't evaluate field XXX in type int`
As far as I understand, it shadow my context variable with the loop iterator variable, and so it does not work.
How am I supposed to do it properly?
How do I pass the value of .
outside of the range loop to template "userdata" when inside a range loop?
答案1
得分: 2
将.
的值分配给一个变量。在循环中使用该变量:
...
{{$x := .}}
{{ range $instance := .Instances }}
- type: instance
metadata:
userdata: {{ template "userdata" $x }}
...
如果.
是模板中的根值,则使用$
来引用该值:
...
{{ range $instance := .Instances }}
- type: instance
metadata:
userdata: {{ template "userdata" $ }}
...
在playground上运行它。
英文:
Assign the value of .
to a variable. Use the variable in the loop:
...
{{$x := .}}
{{ range $instance := .Instances }}
- type: instance
metadata:
userdata: {{ template "userdata" $x }}
...
If .
is the root value in the template, then use $
to refer to that value:
...
{{ range $instance := .Instances }}
- type: instance
metadata:
userdata: {{ template "userdata" $ }}
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论