html/template

Guided tour · Templates · pkg.go.dev →

Same syntax as text/template, but context-aware auto-escaping for HTML, JS, CSS, URL attributes. Use this for web output.

Usage

Auto-escaping

t := template.Must(template.New("p").Parse("<p>{{.}}</p>"))
t.Execute(os.Stdout, "<script>alert(1)</script>")
// Output: <p>&lt;script&gt;alert(1)&lt;/script&gt;</p>

Trusted raw HTML

// Bypass escaping only for values you control:
t.Execute(os.Stdout, template.HTML("<b>bold</b>"))
// Other types: template.JS, template.CSS, template.URL, template.HTMLAttr

Context matters

Escaping is chosen based on where the value appears: attribute, JS literal, URL, etc.

URL context

<a href="{{.URL}}">click</a>
{{/* template refuses unsafe schemes like javascript:... */}}

Parse + serve

With http

t := template.Must(template.ParseFS(tmplFS, "tmpl/*.html"))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    t.ExecuteTemplate(w, "index.html", data)
})