有人知道如何使用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.
我希望呈现以下输出:
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.
虽然我可以用{{ "{{" }}
来避开我想要的文字的每一部分,但感觉有点单调乏味.
我设想我应该能够执行类似I want to render {{template "outer" .Foo}}.
的操作,并调用类似tmpl.ExecuteTemplate(&buff, "outer", data)
的操作,以仅呈现我指定的"外部"操作.
我还想知道呈现"模板的模板"是否是一种代码气味,如果可能的话,我应该用一个字符串/替换来替换我的"外层"模板,比如I want to render <<.Foo>>
.