Home >Backend Development >Golang >How to render 'template of templates' without escaping every operation
php editor Zimo is here to introduce a new technology, that is, how to render "templates of templates" without escaping each operation. During the development process, we often use template engines to render dynamic content, but when we need to use template syntax in templates, we often encounter escaping problems. This article will give you a detailed answer on how to solve this problem so that it can be better applied in project development.
Does anyone know how to use text/template
to render a "template of templates" where only specific actions are rendered (ie: wrapped in {{ ...}}
) and the rest will be processed as text?
For example, given the following 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 the following output:
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.
While I could use {{ "{{" }}
to escape every part of the text I want, it feels a bit tedious.
I think I should be able to do something like I want to render {{template "outer" .foo}}.
and call tmpl.executetemplate(&buff, "outer", data)
or something like that to render only the "external" operations I specify.
I'm also wondering if rendering "template of templates" is a code smell and if possible I should replace my "external" templates with string/replacement like I want to render >
.
You can change the delimiter of the first level template:
tmpl := template.new("name").delims("<<",">>").parse(...)
Then, write the template as:
I want to render <<.Foo>>. but I don't want to render anything on this line, like {{.Bar}}...
The above is the detailed content of How to render 'template of templates' without escaping every operation. For more information, please follow other related articles on the PHP Chinese website!