text/template and html/template

A template is text with actions in double braces: {{.Name}} reads a field, {{if}} and {{range}} choose and repeat, and everything outside the braces is copied as it is. The text/template package is for any text and html/template is the same engine with contextual escaping for a page, which is the difference that keeps a user's input from becoming a script tag.

A template and its data

Parse reads the text once and Execute writes it with a data value, and Must turns a parse error into a panic, which is right for a template compiled into the program. The dot is the data: inside the template .Name is the field of the struct that was passed.

package main import ( "os" "text/template" ) type User struct { Name string Admin bool } func main() { tmpl := template.Must(template.New("greet").Parse("Hello, {{.Name}}!\n")) if err := tmpl.Execute(os.Stdout, User{Name: "ada"}); err != nil { panic(err) } }

go build -o app main.go && ./app

Hello, ada!

The newline in the template is part of the output, which is why the greeting ends with one. A template is compiled once and executed many times, so a server parses its templates at start-up and keeps the *template.Template; a template parsed per request is a small waste of a lot of CPU.

if and range

range repeats its body for every element and rebinds the dot to the element, and if takes the first branch when the value is true and the else branch otherwise. The whitespace control is worth noticing: the newline after {{end}} belongs to the template, so a list that must not have a blank line at the end is written in one line or trimmed with {{- and -}}.

package main import ( "os" "text/template" ) type Page struct { Title string Items []string Admin bool } func main() { tmpl := template.Must(template.New("list").Parse(`{{.Title}} {{range .Items}}- {{.}} {{end}}{{if .Admin}}admin: yes {{else}}admin: no {{end}}`)) data := Page{Title: "Notes", Items: []string{"one", "two"}, Admin: true} if err := tmpl.Execute(os.Stdout, data); err != nil { panic(err) } }

go build -o app main.go && ./app

Notes
- one
- two
admin: yes

The title has no bullet, each item does, and the admin line is the true branch. A false value would print the else branch, and a nil slice would make the range print nothing at all, which is why a template can render an empty list without an extra condition.

text/template against html/template

The two packages parse the same syntax and execute it differently. text/template writes the value as it is; html/template knows that the value sits in an HTML text node and escapes the characters that would end the node. The same input, one line apart, shows the whole difference.

package main import ( htmltemplate "html/template" "os" texttemplate "text/template" ) func main() { value := `<script>alert("x")</script>` text := texttemplate.Must(texttemplate.New("t").Parse("text: {{.}}\n")) if err := text.Execute(os.Stdout, value); err != nil { panic(err) } html := htmltemplate.Must(htmltemplate.New("h").Parse("html: {{.}}\n")) if err := html.Execute(os.Stdout, value); err != nil { panic(err) } }

go build -o app main.go && ./app

text: <script>alert("x")</script>
html: &lt;script&gt;alert(&#34;x&#34;)&lt;/script&gt;

The text line is a script tag and the html line is the text of one. A page built with text/template is an injection waiting for the first user-supplied name; html/template also knows whether the value sits in an attribute, a URL or a script, and applies the right escape for each. The default choice for a page is therefore never the text package.

A missing field

A parse error is about the template, and an execute error is about the data. The template below parses and prints the text before the bad action, and the error names the template, the line and column, the action and the type it was applied to. A program that renders for a user should catch the error and write a fallback rather than half a page.

package main import ( "fmt" "os" "text/template" ) func main() { tmpl := template.Must(template.New("bad").Parse("Hi {{.Missing}}")) err := tmpl.Execute(os.Stdout, struct{ Name string }{Name: "ada"}) fmt.Println("error:", err) }

go build -o app main.go && ./app

Hi error: template: bad:1:5: executing "bad" at <.Missing>: can't evaluate field Missing in type struct { Name string }

The Hi shows that execution is not atomic: the bytes before the failure reached the writer. The fix is either a field that exists or {{with .Optional}}, which skips the body for a missing or empty value; an Execute into a bytes.Buffer and a copy on success makes the output atomic when that matters.

Where templates belong

A template is the right tool when the output is mostly text with a few values and the people who change it are not the people who write the Go: an email, a page, a report, a config file. It is the wrong tool for a JSON API, where encoding/json is faster and cannot produce invalid JSON, and for a format with a grammar that quotes context, where a text template cannot know what to escape. The standard library uses templates for go doc and for the HTML of the pprof pages, which is exactly the shape above.

Two habits pay off. Parse every template at start-up, so a typo is a failure at boot and not a 500 in the first request, and keep the templates in the binary with embed so a release has no directory to find. The next lesson logs the requests this one renders.

Exercises

  1. Add a second item with a quote in its name and render with html/template. What is escaped, and where in the page would the escape differ?
  2. Use {{with .Items}} around the range and render an empty slice. What disappears, and why is that better than a nil check in Go?
  3. Execute the bad template into a bytes.Buffer and print the buffer after the error. How much of the page was written, and what would a handler do with it?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is the dot in a template?

    Answer

    The data value passed to Execute

    Inside a range it becomes the element.

  2. What does template.Must do?

    Answer

    Panics on a parse error

    It is for a template compiled into the program.

  3. What does range bind the dot to?

    Answer

    Each element in turn

    The index is available with $i, .

  4. Which package escapes HTML by default?

    Answer

    html/template

    Contextual escaping is its whole purpose.

  5. Why is text/template wrong for a page?

    Answer

    It writes user input unescaped, so it can inject markup

    html/template is the page renderer.

  6. What does an execute error name?

    Answer

    The template, the position, the action and the type

    It is enough to find the action.

  7. Is Execute atomic?

    Answer

    No, the bytes before the error were written

    Execute into a buffer when the output must be all or nothing.

  8. What does {{with .X}} do for an empty X?

    Answer

    Skips the body

    It is the nil-safe section.

  9. When is a template better than encoding/json?

    Answer

    For mostly-text output such as an email or a page

    A template cannot guarantee valid JSON.

  10. Why parse templates at start-up?

    Answer

    A typo fails at boot instead of in a request

    The same template is executed many times.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev