text/template
- Version
- 1.27
- Review
- Draft
Summary#
text/template fills text from Go data. Actions between {{ and }} read fields, repeat with range and branch with if. Parse a template once and execute it with different values.
Syntax#
{{.Field}}
{{range .Items}} ... {{end}}
{{if gt .Count 0}} ... {{else}} ... {{end}}
Set Option("missingkey=error") to make a missing map key such as {{.user}} an execution error.
Example#
package main
import (
"fmt"
"io"
"os"
"text/template"
)
type line struct {
Name string
Count int
}
var receipt = template.Must(template.New("receipt").Parse(
`Order for {{.Customer}}
{{range .Lines}}- {{.Count}} x {{.Name}}
{{else}}- nothing ordered
{{end}}{{if gt .Total 100}}Free delivery{{else}}Delivery fee applies{{end}}
{{range $key, $value := .Notes}}{{$key}}: {{$value}}
{{end}}`))
func main() {
err := receipt.Execute(os.Stdout, struct {
Customer string
Lines []line
Total int
Notes map[string]string
}{
Customer: "Thu",
Lines: []line{{"notebook", 2}, {"pen", 5}},
Total: 140,
Notes: map[string]string{"gate": "B", "floor": "3"},
})
if err != nil {
fmt.Println(err)
}
strict := template.Must(template.New("strict").
Option("missingkey=error").Parse("{{.user}}"))
err = strict.Execute(io.Discard, map[string]string{})
fmt.Println("missing key rejected:", err != nil)
}
Expected output#
Order for Thu
- 2 x notebook
- 5 x pen
Free delivery
floor: 3
gate: B
missing key rejected: true
Common mistakes#
Templates read exported struct fields only. Check the error from Execute, which may leave partial output behind. text/template does no escaping, so use html/template for HTML and do not execute templates written by untrusted users.
Version applicability#
text/template dates back to Go 1.0. Built-in comparisons such as gt arrived in Go 1.2, and Option("missingkey=error") in Go 1.5. The complete example requires Go 1.16 for io.Discard. A template ranges over maps with keys of an ordered basic type, such as strings, in sorted key order.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0