When rendering HTML using Go templates, you may encounter the perplexing appearance of "ZgotmplZ" in your output. This obscure value stems from a safety measure that detects unsafe content reaching certain contexts, such as CSS or URLs, at runtime.
Consider this example:
func main() { funcMap := template.FuncMap{ "printSelected": func(s string) string { if s == "test" { return `selected="selected"` } return "" }, "safe": func(s string) template.HTML { return template.HTML(s) }, } template.Must(template.New("Template").Funcs(funcMap).Parse(` <option {{ printSelected "test" }} {{ printSelected "test" | safe }} >test</option> `)).Execute(os.Stdout, nil) }
This template will produce the following output:
<option ZgotmplZ ZgotmplZ >test</option>
The presence of "ZgotmplZ" indicates that the unsafe content selected="selected" has reached a CSS context. To handle such scenarios, you can add a "safe" and "attr" function to your template function map:
funcMap := template.FuncMap{ "attr": func(s string) template.HTMLAttr { return template.HTMLAttr(s) }, "safe": func(s string) template.HTML { return template.HTML(s) }, }
Using these functions, you can modify your template as follows:
<option {{.attr | attr}}>test</option> {{.html | safe}}
With this modification, the output will be:
<option selected="selected">test</option> <option selected="selected">option</option>
This solution ensures that unsafe content is properly escaped before being included in the output. You may also consider defining custom functions to convert strings into other types, such as template.CSS, template.JS, and template.URL, to enhance safety and maintain code organization.
The above is the detailed content of Why Does 'ZgotmplZ' Appear in My Go Template Output, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!