Go by Example: Templates
Go has a powerful built-in template engine for generating text or HTML. This example shows how to parse templates, inject data, use actions like range/if, and execute them.
Code
package main
import (
"os"
"text/template"
)
type Inventory struct {
Material string
Count uint
}
func main() {
// 1. Define a simple template
// {{.Count}} accesses the Count field of the data.
// {{- ... -}} trims whitespace.
const tmpl = `
{{- .Count }} items are made of {{ .Material }}
{{ if gt .Count 100 -}}
It is well stocked!
{{- else -}}
We need to restock.
{{- end }}
`
// 2. Create and Parse
// Must handle errors in production code.
t, err := template.New("inventory").Parse(tmpl)
if err != nil {
panic(err)
}
// 3. Execute with Data
sweaters := Inventory{"wool", 17}
err = t.Execute(os.Stdout, sweaters)
if err != nil {
panic(err)
}
// 4. Execute with different Data
// Templates are reusable.
t.Execute(os.Stdout, Inventory{"cotton", 250})
}
Explanation
Go's text/template and html/template packages provide a robust, data-driven engine for generating textual output by executing a template definition against a specific data structure, such as a struct or a map. This system relies on "actions"—commands enclosed in double curly braces {{...}}—to perform logic like conditional execution, iteration over collections, and pipeline processing, where the output of one function is seamlessly passed as the input to the next. The html/template package specifically is engineered for web security, automatically applying context-aware escaping to the injected data to neutralize potential Cross-Site Scripting (XSS) vectors, making it the standard choice for rendering HTML responses in web applications.
The "dot" (.) concept is central to template execution, representing the current context or data item being processed; as the template engine traverses nested structures or iterates over slices using the range action, the value of . dynamically changes to reflect the immediate data scope. This design allows for the creation of highly reusable and modular templates that can adapt to varying data hierarchies, while the ability to define custom functions via a FuncMap extends the language's capabilities, enabling developers to perform complex formatting or logic directly within the presentation layer.
- Actions:
{{ .Field }}to access data. - Control Flow:
{{ if }},{{ range }},{{ with }}. - Pipelines:
{{ .Value | func }}passes data to functions. - Security: Always use
html/templatefor web output to prevent XSS.

