【问题标题】:Share variables between golang templates在 golang 模板之间共享变量
【发布时间】:2019-09-24 23:00:22
【问题描述】:

我想用 GOtemplate 生成 2 个单独的文件,假设我有这个代码:

aBuffer := new(bytes.Buffer)
bBuffer := new(bytes.Buffer)

aTmpl, _ := template.ParseFiles(aFilePath)
aTmpl.Execute(aBuffer, someVariables)

bTmpl, _ := template.ParseFiles(bFilePath)
bTmpl.Execute(bBuffer, someVariables)

假设我为这两个文件使用了一个通用 var(不是来自“someVariables”golang var),我有没有办法像 Helm 一样在单独的文件中声明它?

{{ define myVar }}
the-var
{{ end }}

然后保持一种我可以在 aTmpl 和 bTmpl 中重复使用的上下文:

{{ template myVar .}}

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

    使用通用定义创建第三个文件:

    {{define "myVar"}}
    the-var
    {{end}}
    

    与其他文件一起解析该文件:

    aTmpl, _ := template.ParseFiles(aFilePath, commonFilePath)
    
    bTmpl, _ := template.ParseFiles(bFilePath, commonFilePath)
    

    在两个模板中使用“myvar”如下:

    {{template "myVar" .}}
    

    【讨论】:

    • 我觉得自己太笨了,应该考虑一下..谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 2022-11-30
    • 2016-09-19
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多