Home >Backend Development >Golang >Why Does 'ZgotmplZ' Appear in My Go HTML Templates, and How Can I Fix It?
When a Go template function outputs HTML, the unexpected appearance of "ZgotmplZ" may arise. This peculiar value indicates the presence of unsafe content within a CSS or URL context during runtime.
"ZgotmplZ" signifies that raw, potentially dangerous data has erroneously entered a CSS or URL context. To remedy this, the safe and attr functions must be added to the template's funcMap. These functions convert the data to safe HTML and HTML attributes, respectively.
package main import ( "html/template" "os" ) func main() { funcMap := template.FuncMap{ "attr": func(s string) template.HTMLAttr { return template.HTMLAttr(s) }, "safe": func(s string) template.HTML { return template.HTML(s) }, } template.Must(template.New("Template").Funcs(funcMap).Parse(` <option {{.attr | attr}}>>test</option> {{.html | safe}} `)).Execute(os.Stdout, map[string]string{ "attr": `selected="selected"`, "html": `<option selected="selected">test</option>`, }) }
This corrected code will generate the desired output:
<option selected="selected">test</option> <option selected="selected">test</option>
Developers may opt to define additional functions that can convert strings to other HTML-safe types such as template.CSS, template.JS, template.JSStr, and template.URL.
The above is the detailed content of Why Does 'ZgotmplZ' Appear in My Go HTML Templates, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!