liveBook · Manning

Text/template package

As explained in Learn Go with Pocket-Sized Projects

A Go template is a text-processing specification whose actions are evaluated against supplied data to produce formatted output.

When a large piece of mostly static text needs a few dynamic values, a template is often clearer than assembling strings with fmt.Sprintf or strings.Builder. Go’s text/template package parses text containing actions such as {{ . }} and executes it against supplied data to produce output. section 11.1.2 section 11.6

A small template follows a direct workflow:

  • Keep the template in a separate file, optionally load it with //go:embed, then call template.New("name").Parse(contents). Handle parse errors before producing output. section 11.1.2 section 11.6
  • Call Execute(writer, data) and handle its error. Within the template, {{ . }} prints the current value; {{ .Field }} reads an exposed field. section 11.1.2 section 11.2.2
  • Use {{ range . }} … {{ end }} to repeat output for a collection. Inside the range, dot becomes the current item; {{- and -}} can trim unwanted whitespace. section 11.2.2

Generate a stylesheet

A styles.css template can set background-color: {{.Background}} and color: {{.Foreground}}. An HTTP handler parses the embedded file with text/template, sets Content-Type to text/css, then executes it with Background and Foreground values. The result is CSS assembled without concatenating the stylesheet in Go code. section 11.5.3

Listing 11.48 styles.go: Applies the CSS
import (
    _ "embed"
    "text/template" #1
    ...
)

//go:embed templates/styles.css
var stylesPage string

func (s *Server) styles(w http.ResponseWriter, r *http.Request) {
    tpl, err := template.New("styles").Parse(stylesPage)
    if err != nil {...}

    w.Header().Add("Content-Type", "text/css") #2

    err = tpl.Execute(w, map[string]interface{}{
        "Background":"DarkSlateGray",
        "Foreground":"LightGray"}) #3
    if err != nil {...}
}

The handler shows the package import, parse-and-execute calls, data map, and CSS response header together. section 11.5.3

Choose html/template instead when rendering HTML: it shares the template interface but escapes values to protect the page from HTML injection. text/template does not provide that protection, so consider whether values are safe for the format being generated. Templates also depend on exposed Go field names; renaming or hiding a field breaks its use in the template. Although methods can be called under return-value constraints, keeping complex calls out of templates makes them easier to read. section 11.1.2 section 11.2.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Works through parsing and execution, actions, fields, iteration, and a CSS handler; does not descend into package internals.
Examples
Uses a habits list and an embedded stylesheet whose background and foreground colors come from supplied data.
What it assumes
Assumes familiarity with Go structs and HTTP handlers while introducing template actions through simple values and fields.
What you can do after
Apply it via text/template to parse a separate template file and execute it with data in an HTTP response.
How it connects
Connects template actions to Go structs, embed, HTTP handlers, and html/template’s HTML-escaping behavior.

Also explained in

Compare how 2 books explain text/template package →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.