Go Reference ยท bytes, unicode and text
Go text/template package
Reference for Go text/template: parse templates, actions, pipelines, range, if, with, variables, custom functions, nested templates and error handling.
The package text/template turns a template, plain text with {{ actions }} in it, plus a data value into output text. You parse the template once, then execute it as many times as you like with different data. Use it for emails, configuration files, reports and code generation. For HTML, use html/template, which has the same API but escapes values for the context they appear in.
The typical flow is template.New(name).Parse(text) followed by tmpl.Execute(w, data). Inside the template, a dot (.) is the current value: the data you passed at the top, and something else inside range and with.
t := template.Must(template.New("hi").Parse("Hello, {{.Name}}!\n")) t.Execute(os.Stdout, map[string]string{"Name": "Ada"})
Try it
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.
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.
Syntax
func New(name string) *Template func Must(t *Template, err error) *Template func (t *Template) Parse(text string) (*Template, error) func (t *Template) Funcs(funcMap FuncMap) *Template func (t *Template) Execute(wr io.Writer, data any) error func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error func (t *Template) Option(opt ...string) *Template
Template actions, all between {{ and }}:
| Action | Description |
|---|---|
{{.}}, {{.Field}}, {{.Key}} |
Print the current value, a struct field, a map key or a method result. Chains like .A.B work. |
{{$x := pipeline}} |
Declare a variable; reassign with =. $ itself is the data passed to Execute. |
{{if p}}...{{else if q}}...{{else}}...{{end}} |
Conditional. False values are false, 0, nil, and empty array, slice, map or string. |
{{range p}}...{{else}}...{{end}} |
Loop over a slice, array, map (sorted keys), channel, integer or iterator function. else runs when empty. {{range $i, $v := p}} names the index and value. |
{{with p}}...{{else}}...{{end}} |
Run the body with . set to p when p is non-empty. |
{{define "n"}}...{{end}}, {{template "n" arg}} |
Declare and call a named template. {{block "n" arg}}...{{end}} defines and calls in one step. |
{{break}}, {{continue}} |
Control a range loop. |
{{/* comment */}} |
Comment. |
{{- and -}} |
Trim whitespace before or after the action. A space must separate the dash from the action. |
Pipelines chain with |: {{.Name | printf "%q"}} passes the value as the last argument of printf.
Built-in functions: and, or, not, eq, ne, lt, le, gt, ge, len, index, slice, print, printf, println, html, js, urlquery, call.
Errors: Parse returns syntax errors and unknown-function errors. Execute returns errors such as a missing struct field (can't evaluate field Age in type main.P) or a failed method call. By default a missing map key prints <no value>; Option("missingkey=error") makes it an error.
Usage notes
- Parse once, execute many times. A parsed
*Templateis safe for concurrentExecutecalls. Parsing inside a request handler wastes time. template.Mustpanics if parsing fails, which is the right behavior for templates that are package-level variables.- Only exported fields and methods are visible to templates.
{{.name}}cannot see a field calledname. - Output may be partial on error. Execution writes as it goes, so a failure in the middle leaves the first part already written. Execute into a
bytes.Bufferfirst if you need all-or-nothing. - Comparisons are strict about types.
eqcan compare basic kinds of the same family (all signed ints, all strings), but anintand afloat64produce an error.eq a b cmeansa == b || a == c. - Functions must be registered before
Parse. CallFuncsfirst, otherwise the parser reportsfunction "x" not defined. - Not safe for HTML.
text/templatedoes no escaping. For web pages usehtml/template; do not build HTML with this package. - Files:
template.ParseFiles,ParseGlobandParseFSload templates from disk or anembed.FS. The runner on this site has no extra files, so examples use strings. - Delimiters can be changed with
Delims("[[", "]]")when your output already contains braces, for example JSON or Go code.
Related
fmt.Printf(),strings,bytes.Buffer,range- Lessons: Text templates