Go's text/template and html/template packages generate dynamic text from a template and a data value. You parse a template once, then execute it with a struct, map or slice, and actions written between {{ and }} insert values, branch with if, and loop with range. Use text/template for plain text such as emails and config files, and html/template for anything sent to a browser, because it escapes output for the context it lands in.
Go has no package literally named template. Both packages share the same syntax and API, so everything below applies to each unless noted.
| Package | Use it for | Escaping |
|---|---|---|
text/template | Emails, config files, code generation, CLI output | None; output is written as is |
html/template | Web pages, HTML emails | Contextual escaping for HTML, attributes, JavaScript, CSS and URLs |
Never build web pages with text/template. If user input reaches the output, you create a cross-site scripting hole. html/template has the same API but rewrites each action so that a value placed inside an attribute or a script block is escaped for that context.
The basic flow is template.New, Parse, then Execute. Always check both errors.
The dot (.) is the current data value. Inside range, the dot becomes the current element. Only exported struct fields (capitalised names) are accessible; an unexported field makes Execute return an error.
If a template is a fixed part of your program, use template.Must(template.New(...).Parse(...)) at package level so a typo fails at startup rather than at request time.
Common actions:
{{.Field}} and {{.Map.key}} print a field or map entry.{{if .X}}...{{else if .Y}}...{{else}}...{{end}} branch. Empty values (false, 0, nil, empty string, empty slice or map) count as false.{{range .Items}}...{{else}}...{{end}} loop; the else branch runs when the collection is empty.{{with .Value}}...{{end}} runs only when the value is non-empty and rebinds the dot.{{$x := .Total}} declares a variable that you can use later in the same block.{{- ... -}} trims whitespace on the left and right of an action.Pipelines pass the result of one command as the last argument to the next, like a Unix pipe:
Built-in functions include and, or, not, len, index, slice, printf, print, println, eq, ne, lt, le, gt, ge, html, js, urlquery and call. Comparison functions are written in prefix form: {{if gt .Qty 10}}bulk{{end}}.
Since Go 1.23, range over integers and functions (range-over-func iterators) also works in templates, so check your Go version before relying on it.
Register functions with Funcs before you call Parse, otherwise parsing fails with a "function not defined" error.
A template function must return one value, or two where the second is an error. If the error is non-nil, execution stops and Execute returns it.
Switch the import to html/template and the same code becomes safe for HTML output.
If name is <script>alert(1)</script>, the browser receives <script>alert(1)</script>. The Query value is URL-escaped because it sits in a URL inside an attribute. The types template.HTML, template.URL and template.JS mark a string as already safe; only use them for content you fully control.
Real sites split templates into files. Use define and template to compose them, and embed to ship them inside the binary.
In templates/layout.html, write {{template "header" .}} to include a block defined elsewhere with {{define "header"}}...{{end}}, and pass the dot explicitly. Use {{block "content" .}}default{{end}} for a slot that other templates override.
Parse templates once at startup and reuse them. Templates are safe for concurrent Execute calls. To avoid sending half-written output when execution fails, render into a bytes.Buffer first and copy it to the response on success.
They share syntax and API. html/template additionally escapes values for the HTML, attribute, JavaScript, CSS or URL context where they appear, which prevents cross-site scripting. text/template writes values unchanged.
Usually the field is unexported (lower case) or misspelled. Use capitalised field names, and call Option("missingkey=error") on map-based data to make missing keys fail loudly.
Add a hyphen next to the delimiter: {{- .X -}} removes whitespace before and after the action, including newlines.
Yes. {{.User.FullName}} calls the exported method FullName on the value, and {{.Total 10}} passes arguments. The method must return one value, or a value and an error.
Parse templates once, execute them with structs or maps, and use {{if}}, {{range}}, {{with}} and pipelines to shape output. Choose html/template for browsers so escaping happens automatically, register helpers through FuncMap before parsing, and compose pages with define, template and embed. Check the errors from Parse and Execute every time.