登录
首页 >  Golang >  Go问答

在 Go 模板的循环中调用子模板

来源:stackoverflow

时间:2024-04-12 21:54:34 170浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《在 Go 模板的循环中调用子模板》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

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

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

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

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

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

上面以错误消息结束,如下所示:

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

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

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

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


正确答案


. 的值分配给变量。在循环中使用变量:

...
{{$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

今天关于《在 Go 模板的循环中调用子模板》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>