mod*_*tos 1 templates go go-templates
有谁知道如何使用 渲染“模板的模板” ,其中仅渲染text/template特定操作(即:包裹在 中的内容),其余部分将被视为文字?{{...}}
例如,给定以下模板:
I want to render {{.Foo}}.
but I don't want to render anything on this line, like {{.Bar}} or this template: [{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}
Render {{.Foo}} again.
Run Code Online (Sandbox Code Playgroud)
我想呈现以下输出:
I want to render foo.
but I don't want to render anything on this line, like {{.Bar}} or this template: [{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}
Render foo again.
Run Code Online (Sandbox Code Playgroud)
虽然我可以使用 转义我想要的文字的每个部分{{ "{{" }},但感觉有点乏味。
我想我应该能够执行类似的操作I want to render {{template "outer" .Foo}}.并调用类似的操作tmpl.ExecuteTemplate(&buff, "outer", data)来仅呈现我指定的“外部”操作。
我还想知道渲染“模板的模板”是否是一种代码味道,如果可能的话,我应该用字符串/替换来替换我的“外部”模板,例如I want to render <<.Foo>>.
您可以更改第一级模板的分隔符:
tmpl := template.New("name").Delims("<<",">>").Parse(...)
Run Code Online (Sandbox Code Playgroud)
然后,将模板编写为:
I want to render <<.Foo>>.
but I don't want to render anything on this line, like {{.Bar}}...
Run Code Online (Sandbox Code Playgroud)