【问题标题】:Calling subtemplates from within a loop in Go template从 Go 模板的循环中调用子模板
【发布时间】:2021-12-07 16:01:48
【问题描述】:

当我在{{ range }} 循环之外导入子模板时,变量在导入的模板中成功传递:

...
 {{ template "userdata" . }}
...

(在这里,我可以在内部模板userdata 中访问我的外部模板变量)。到目前为止一切顺利。

但是,当在 {{ range }} 循环中调用时,相同的时尚导入不起作用:

...
{{ range $instance := .Instances }}
- type: instance
  metadata:
    userdata: {{ template "userdata" . }}
...

上面以错误消息结束,例如:

Error: template: template.tmpl:3:46: executing "userdata" at <XXX>: can't evaluate field XXX in type int`

据我了解,它用循环迭代器变量遮蔽了我的上下文变量,因此它不起作用。

我应该如何正确地做到这一点?

在范围循环内时,如何将范围循环外的. 的值传递给模板“userdata”?

【问题讨论】:

  • @CeriseLimón:绝对!

标签: go templates


【解决方案1】:

. 的值赋给一个变量。在循环中使用变量:

...
{{$x := .}}
{{ range $instance := .Instances }}
- type: instance
  metadata:
    userdata: {{ template "userdata" $x }}
...

如果. 是模板中的根值,则使用$ 来引用该值:

...
{{ range $instance := .Instances }}
- type: instance
  metadata:
    userdata: {{ template "userdata" $ }}
...

Run it on the playground.

【讨论】:

  • 这两个选项都有效!
猜你喜欢
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
  • 2016-04-08
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多