Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Encoding and Data Formats

The Go html/template package

Reference for Go's html/template package: contextual auto-escaping, template.HTML and other safe types, funcs, nested templates, ExecuteTemplate and errors.

html/template has the same template language as text/template (actions in {{ }}, pipelines, range, if, with, define), but it understands HTML. As it executes, it escapes every value for the exact place where it appears: HTML text, an attribute, a URL, a JavaScript string or a CSS value. That prevents most cross-site scripting (XSS) bugs without you remembering to escape anything.

Use html/template whenever the output is shown in a browser. Use text/template for everything else (e-mails in plain text, config files, code generation), because it never escapes.

Go
t := template.Must(template.New("hi").Parse("<p>{{.}}</p>\n"))
t.Execute(os.Stdout, "<b>x</b>") // <p>&lt;b&gt;x&lt;/b&gt;</p>

Try it

Go Escaping depends on the context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Safe types, functions and nested templates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func New(name string) *Template
func Must(t *Template, err error) *Template
func ParseFiles(filenames ...string) (*Template, error)
func ParseGlob(pattern string) (*Template, error)
func ParseFS(fsys fs.FS, patterns ...string) (*Template, error)

func (t *Template) Parse(text string) (*Template, error)
func (t *Template) Funcs(funcMap FuncMap) *Template
func (t *Template) Option(opt ...string) *Template
func (t *Template) Delims(left, right string) *Template
func (t *Template) Execute(wr io.Writer, data any) error
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error
func (t *Template) Lookup(name string) *Template
func (t *Template) Clone() (*Template, error)

type HTML string; type HTMLAttr string; type JS string; type CSS string; type URL string; type JSStr string; type Srcset string
func HTMLEscapeString(s string) string
func JSEscapeString(s string) string
Name Description
name Template name. Files get the base name of the file.
data The value available as . in the template: a struct, map, slice or any other value.
FuncMap map[string]any of functions callable from templates. Each must return one value, or a value and an error.
Option("missingkey=error") Fail on a missing map key instead of printing <no value>.

Errors and edge cases:

  • Escaping is decided on the first Execute; after that, Parse on the same template returns an error. Parse everything first.
  • A template that cannot be escaped safely (for example an action inside a JavaScript regular expression, or a branch that ends in a different context than it started) fails at Execute time with an ErrorCode-based error.
  • Writing output to wr can fail halfway, and part of the page may already be sent. Render into a bytes.Buffer first when you need an all-or-nothing response.
  • Calling a missing template name returns an error from ExecuteTemplate.

Usage notes

  • Never convert untrusted input to template.HTML, template.JS or template.URL. These types tell the package "I vouch for this". Marking user text as template.HTML switches off protection.
  • Values in href and src: unsafe schemes such as javascript: are replaced by #ZgotmplZ. If you see that text in your output, the package refused a value it considered dangerous. Fix the data or use template.URL only for values you built yourself.
  • Comments: HTML comments in the template text are removed from the output; Go template comments are {{/* ... */}}.
  • Layouts: parse a base template with {{block "content" .}} and clone it per page, or use ParseFiles("layout.html", "page.html"). Calling ExecuteTemplate(w, "layout.html", data) renders the layout.
  • Parse once, execute many times. Parsing is slow; a parsed *Template is safe for concurrent Execute calls. Parse at start-up, not per request.
  • Embedding: combine ParseFS with //go:embed to ship templates inside the binary.
  • Not a sanitizer. It escapes text; it does not remove tags from user-supplied HTML. If you must allow some markup, run it through an HTML sanitizer first.