Use contextual HTML escaping
Use contextual HTML escaping
Use html/template rather than text/template to render HTML from trusted template source and untrusted ordinary string data. The package chooses escaping based on the surrounding HTML, attribute, URL, CSS or JavaScript context. This is output encoding, not validation of the business meaning of data. In the examples ht is an import alias for html/template.
package main
import ( "bytes" "fmt" ht "html/template")
func check(e error) { if e != nil { panic(e) }}
func main() { t, e := ht.New("card").Parse(`<p>{{.}}</p>`) check(e) var b bytes.Buffer check(t.Execute(&b, "Tea & <rice>")) fmt.Println(b.String())}The ampersand and angle brackets become HTML entities, so the browser displays them as text instead of interpreting the value as markup. Pass the original plain string; pre-escaping it can cause double encoding. Never convert arbitrary user content to template.HTML to suppress escaping.
Expected output:
<p>Tea & <rice></p>Escaping differs by context
package main
import ( "bytes" "fmt" ht "html/template")
func check(e error) { if e != nil { panic(e) }}
func main() { t, e := ht.New("link").Parse(`<a href="/search?q={{.}}">{{.}}</a>`) check(e) var b bytes.Buffer check(t.Execute(&b, "tea & rice")) fmt.Println(b.String())}The query component gets URL encoding, while the link label receives HTML text escaping. Context is derived from the trusted template, not from a manual escape call. Keep URL destination policy, authorization, content security policy and data validation separate. Unsafe typed values (such as template.URL or template.HTML) assert trust and can bypass normal protections; use plain strings for ordinary data. Check execution errors before sending a response.
Expected output:
<a href="/search?q=tea%20%26%20rice">tea & rice</a>Try it locally
Render <strong>{{.}}</strong> with the plain string A & B, then print the HTML.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Text processing 06: Use contextual HTML escaping
Check the lesson objective before moving on.
Which package is intended for rendering HTML with contextual escaping?
What should you pass for an ordinary user-supplied title?