在 golang 模板之间共享变量

Share variables between golang templates

我想用 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)

假设我对这两个文件使用了一个通用变量(不是来自 "someVariables" golang 变量),我是否有办法像 Helm 一样在单独的文件中声明它?

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

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

{{ template myVar .}}

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

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

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

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

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

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

{{template "myVar" .}}