Web application security · 6 MIN READ

html/template escapes by context, and template.HTML is where that protection switches off

Render untrusted data with html/template, read its context-specific escaping and treat every typed-content conversion as a reviewed trust decision.

Cross-site scripting happens when data from one user becomes markup or script in another user's browser. Escaping is the defense, but the correct escaping depends on where a value lands: a text node, a quoted attribute, a URL, a JavaScript string and a CSS value each have different metacharacters. Go's html/template parses your template, tracks that context at every action and applies the matching escaper automatically. text/template does none of this, and typed strings such as template.HTML tell html/template to stop.

security · A MAP OF THE IDEA

  1. Parse trusted template
  2. Pass untrusted data
  3. Escape per context
  4. Review typed content

Useful when

  • The escaper follows text, attribute, URL, JS and CSS contexts automatically.
  • Unsafe URL schemes are neutralized instead of rendered as clickable links.

Watch out

  • template.HTML, JS and URL conversions disable escaping without checking anything.
  • Frontend code that uses innerHTML is outside html/template's protection.

Implementation & operation cost: Templates must be valid, analyzable HTML and rich user content needs a separate sanitizer; the escaping itself is cheap.

01

One payload, four different meanings

Take a display name such as <img src=x onerror=alert(1)>. In a text node its angle brackets must be entity-encoded. In a quoted attribute the quote character matters most. Inside a <script> block HTML entities mean nothing, so the value must become a correctly escaped JavaScript string. In an href the danger is not a character at all but the scheme: a javascript: URL runs code when clicked. An escaping function that is right for one of these contexts is wrong for another, which is why calling html.EscapeString on everything and concatenating strings is not a defense. The engine that writes the page has to know where each value is going.

02

Render the same data with text/template and html/template

The program parses one template text with both packages and executes it with the same hostile data: a name carrying an event-handler payload, a javascript: link, a search query with spaces and an ampersand, and a staff-written biography typed as template.HTML. Comparing the two outputs line by line shows what html/template decided in each context.

go
package main

import (
	"fmt"
	htmltemplate "html/template"
	"strings"
	texttemplate "text/template"
)

const page = `<p title="{{.Name}}">Hi {{.Name}}</p>
<a href="{{.Site}}">home</a> <a href="/search?q={{.Query}}">find</a>
<script>const user = {{.Name}};</script>
<div>{{.Bio}}</div>`

type profile struct {
	Name  string
	Site  string
	Query string
	Bio   htmltemplate.HTML // a trust assertion: rendered without escaping
}

func main() {
	data := profile{
		Name:  `<img src=x onerror=alert(1)>`,
		Site:  "javascript:alert(document.cookie)",
		Query: "go & rust",
		Bio:   htmltemplate.HTML(`<b>written by staff</b>`),
	}

	var unsafe strings.Builder
	t := texttemplate.Must(texttemplate.New("page").Parse(page))
	if err := t.Execute(&unsafe, data); err != nil {
		panic(err)
	}
	fmt.Println("text/template:")
	fmt.Println(unsafe.String())

	var safe strings.Builder
	h := htmltemplate.Must(htmltemplate.New("page").Parse(page))
	if err := h.Execute(&safe, data); err != nil {
		panic(err)
	}
	fmt.Println("html/template:")
	fmt.Println(safe.String())
}
Read the code

text/template copies every value verbatim: the image tag would run in the paragraph, a payload containing a double quote would break out of the title attribute, and the script block becomes invalid JavaScript containing markup. html/template entity-encodes the name in both the text node and the attribute. In the first href it inspects the scheme, refuses javascript: and substitutes #ZgotmplZ, a deliberately meaningless marker. In the query string it percent-encodes the value, so & cannot start a new parameter. Inside <script> it emits a quoted JavaScript string with < and > written as \u003c and \u003e, so the browser never sees a tag. The Bio line is identical in both outputs because template.HTML told html/template the value is already safe markup.

03

#ZgotmplZ is a refusal, not a bug to silence

ZgotmplZ is the innocuous word html/template emits when an unsafe value reaches a URL, CSS or attribute-name position at run time. In URL attributes the filter passes relative references and the http, https and mailto schemes; javascript:, data: and every other scheme become #ZgotmplZ. Seeing it in rendered HTML means the data and the template disagree about what is allowed, so fix the data or the design instead of reaching for a conversion. html/template also refuses templates it cannot analyze: a template that ends inside an unclosed tag or attribute, an action in an ambiguous part of a URL, or if branches that leave the parser in different contexts make Execute return an error. Treat those errors as defects caught before any browser saw the page.

04

Typed content is a trust assertion

html/template skips escaping for values of type template.HTML, HTMLAttr, URL, JS, JSStr, CSS and Srcset in their matching contexts. The conversion checks nothing; it is a claim, made by whoever wrote it, that the string is already safe there. That claim is correct for markup your own code generated, for the output of another executed template and for the output of a maintained HTML sanitizer. It is wrong for user input, for rows another service wrote, for Markdown rendered without sanitizing and for JSON pasted into a script as template.JS. Keep conversions rare, next to the code that produced the value and easy to search for, so a reviewer can list every place the escaper is switched off.

go
// Reviewable: the conversion sits next to the sanitizer that justifies it.
func renderBio(markdown string) template.HTML {
	unsafeHTML := markdownToHTML(markdown) // may contain <script>
	return template.HTML(policy.Sanitize(unsafeHTML))
}

// Dangerous: a trust assertion about data nobody checked.
data := map[string]any{"Bio": template.HTML(r.FormValue("bio"))}
Read the code

This fragment runs in your own service; markdownToHTML and policy stand for a Markdown renderer and an allow-list HTML sanitizer such as bluemonday, neither of which is in the standard library. The first function keeps the conversion beside the sanitizer that justifies it. The last line is the pattern to search for in review: a request value converted to template.HTML reintroduces exactly the XSS that html/template was preventing.

05

What html/template does not cover

html/template assumes the template text is trusted and only the data is not, so never parse a template from user input. Its guarantees end at the HTML it writes. A JSON API whose data the frontend inserts with innerHTML is DOM-based XSS, and the fix lives in that JavaScript. A handler that writes user bytes with w.Write or Gin's c.Data and a text/html content type bypasses templates entirely, and an uploaded file served from your origin needs a correct Content-Type plus X-Content-Type-Options: nosniff, ideally from a separate download domain. In Gin, c.HTML renders through html/template, so templates loaded with LoadHTMLGlob get contextual escaping, while c.String responds as text/plain. A Content-Security-Policy, covered in the headers lesson, is the second layer for the day an escaping decision goes wrong.

06

Review and test escaping

In review, look for text/template imports in packages that produce HTML, for template.HTML, JS and URL conversions, and for handlers that set Content-Type to text/html by hand. In tests, render each template with a fixed set of hostile values: angle brackets, both quote characters, a javascript: URL and a closing </script>. Assert on the exact output, as the program prints it, so an edit that moves an action into a new context shows up as a diff. A golden-file test per template is cheap and catches the regression a human reviewer is least likely to notice.

TAKE THIS WITH YOU

Render HTML only with html/template, let it choose the escaper for each context, and treat every template.HTML, JS or URL conversion as a reviewed claim that the value is already safe.

Check your understanding

A profile page renders a user's website link as href="#ZgotmplZ". What happened?

Go to the source

Progress stays in this browser. No account needed.