Calling subtemplates from within a loop in Go template

huangapple go评论86阅读模式
英文:

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" $ }}
...

Run it on the playground.

huangapple
  • 本文由 发表于 2021年10月21日 04:29:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/69652647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定