Skip to content
Tutorials Center
My learning

Topics

Lesson 83 of 147 ยท Standard Library

Templates: text/template and html/template

Learn Go templates - actions, pipelines, range, if and with, variables, custom functions, nested templates with define and block, and why html/template auto-escaping protects against XSS.

A template is a text with holes in it. You write the fixed parts once (an email, a report, a web page, a config file) and mark the places where data goes; at run time Go fills the holes from a value you pass in. The standard library has two packages for this with the same syntax: text/template for plain text of any kind, and html/template for HTML, which adds automatic escaping so that data can't inject markup or scripts.

Learn the syntax once with text/template, and then see why html/template is the only correct choice for web pages.

Your first template

Parse a template string, then execute it with some data and a destination (io.Writer). Anything between {{ and }} is an action; the dot . stands for the data you passed in.

Go Fields, methods and Execute

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.

{{.Customer}} reads an exported field, and {{.Label}} calls a method (with no arguments, or with the arguments written after it). Fields must be exported, since the template package uses reflection from outside your package. template.Must wraps a call returning (*Template, error) and panics on error, which is the idiom for templates defined in source code.

Parse errors appear when you parse; most execution errors (such as a missing field) only appear at run time, so test your templates.

Control flow: if, range and with

Actions can branch and loop. Each block ends with {{end}}.

  • {{if cond}}...{{else if cond}}...{{else}}...{{end}}: the condition is "true" for any non-empty value: true, a non-zero number, a non-nil pointer, a non-empty string, slice or map.
  • {{range .Items}}...{{else}}...{{end}}: loops over a slice, array, map (in sorted key order), channel or integer, setting . to each element. The else part runs when there are no elements.
  • {{with .Field}}...{{end}}: runs the body only if the value is non-empty, with . set to it.
  • {{break}} and {{continue}} work inside range.

By default, the text around actions is kept exactly, including newlines. A trim marker ({{- or -}}) removes the whitespace on that side:

Go if, range, with and trim markers

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.

$i and $it are variables declared in the range header; they let you reach the loop's values even after . changes inside a nested with. A variable named $ always refers to the data passed to Execute, handy for reaching outer fields from inside a loop.

Notice gt $it.Stock 0: in templates, comparisons are functions written in prefix form: eq, ne, lt, le, gt, ge. eq accepts several values (eq .Role "admin" "owner" means "equals either"). Combine conditions with and, or and not.

Pipelines and built-in functions

Like a shell, a template can send a value through a chain of functions with |. The result of each step becomes the last argument of the next:

{{.Name | printf "%q" | len}} is the same as {{len (printf "%q" .Name)}}.

Use parentheses to group. Built-in functions include printf, print, println, len, index (slice, array or map element), slice, html, js, urlquery, call and the comparison and logic functions above.

Go Pipelines, index and custom functions

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.

Functions registered with Funcs must be added before parsing, because the parser checks that every function name exists. A function may return one value, or a value and an error; a non-nil error stops execution.

Map keys are visited in sorted order by range in templates, so template output of maps is deterministic. That is different from a for range loop in Go code, where map order is random.

Nested templates: define, template and block

Templates can contain other templates. {{define "name"}}...{{end}} declares a named template and {{template "name" .}} calls it, passing data (note the dot; without it the called template sees nothing). {{block "name" .}}default{{end}} defines and calls in one step, so another definition can override the default. This is how page layouts work:

Go Layout with define, template and block

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.

The same idea scales up with template.ParseFiles, ParseGlob and, in real programs, embed.FS with ParseFS, so templates ship inside your binary. Name templates after their file names and keep the layout (header, footer, navigation) in one place.

When data is missing

Looking up a missing map key or a nil value is not an error by default: it prints <no value>. Set Option("missingkey=error") to get an error instead, which catches typos early:

Go missingkey and execution errors

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.

Note that the error is returned only after part of the output has already been written. If you write to an HTTP response, render into a bytes.Buffer first and copy it to the client once execution succeeded.

html/template and automatic escaping

For HTML, import html/template instead. The API is identical, but the package understands HTML, CSS, JavaScript and URL contexts and escapes each value for the place where it appears. This stops cross-site scripting (XSS), the attack in which user input such as <script>steal()</script> is injected into your page.

Go text/template versus html/template

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.

The safe version escapes the angle brackets in the body, the quote in the attribute, percent-encodes the query parameter, replaces the javascript: link by a harmless #ZgotmplZ placeholder and turns the value in the script into a JSON string. You wrote one template and got four different escapings.

If you have HTML that you trust (rendered from Markdown by your own code, for example), wrap it in template.HTML to skip escaping. That's an explicit promise that the text is safe: never apply it to anything a user typed.

Use html/template for every template that produces HTML, even in internal tools. text/template writes values verbatim, so one unescaped comment field can become a stored-XSS hole. Also, never build a template from user input: templates can call methods on your data, so the template text must be trusted code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does {{.name}} fail to read the field name string of a struct passed to Execute?

    The template package uses reflection from outside your package, so it can only see exported (capitalized) fields.
  2. 2. What does {{range .Items}}x{{else}}none{{end}} print for an empty slice?

    The else branch of range runs when there are no elements.
  3. 3. What does the marker in {{- .Name -}} do?

    A hyphen next to the braces removes the adjacent whitespace, including newlines, from the template's text.
  4. 4. How do you write the comparison Stock > 0 in a template?

    Comparisons are functions in prefix form: gt, lt, ge, le, eq, ne.
  5. 5. Which package should render a web page that includes user comments?

    html/template escapes automatically and stops XSS. text/template writes values as they are.

Summary

  • Parse a template (template.New(name).Parse(text), template.Must for fixed templates) and run it with Execute(w, data).
  • {{.Field}} reads exported fields, map keys and methods; $ is the root data and $x := ... declares variables.
  • if, else if, range (with else), with, break and continue control the flow; {{- and -}} trim whitespace.
  • Comparisons and logic are prefix functions (eq, gt, and, not); pipelines chain functions with |; add your own with Funcs, before parsing.
  • define, template and block compose templates; ExecuteTemplate runs one by name.
  • Option("missingkey=error") turns typos in map keys into errors.
  • Always use html/template for HTML: it escapes per context and prevents XSS; template.HTML bypasses it, so use it only for trusted markup.

Next: Logging with log and slog covers how to record what your program is doing.