text/template

Guided tour · Templates · pkg.go.dev →

Generic text templating. Use html/template instead for anything rendered as HTML (auto-escapes).

Parse and execute

Simple

t := template.Must(template.New("greet").Parse("hello {{.Name}}\n"))
t.Execute(os.Stdout, map[string]string{"Name": "Ada"})

From files

t := template.Must(template.ParseFiles("layout.tmpl", "body.tmpl"))
t.ExecuteTemplate(os.Stdout, "layout.tmpl", data)

From embed.FS

//go:embed tmpl/*.tmpl
var tmplFS embed.FS
t := template.Must(template.ParseFS(tmplFS, "tmpl/*.tmpl"))

Actions

Conditionals and ranges

{{if .LoggedIn}}hi {{.Name}}{{else}}sign in{{end}}
{{range .Items}}- {{.}}
{{else}}no items{{end}}
{{with .User}}{{.Email}}{{end}}

Pipelines and funcs

{{.Title | printf "%q"}}
{{len .Items}}
{{index . "key"}}

Variables

{{$name := .Name}}
{{range $i, $v := .Items}}{{$i}}={{$v}} {{end}}

Custom functions

Funcs

funcs := template.FuncMap{
    "upper": strings.ToUpper,
    "join":  strings.Join,
}
t := template.Must(template.New("x").Funcs(funcs).Parse("{{upper .Name}}"))

Partials / composition

define + template

{{define "header"}}<h1>{{.Title}}</h1>{{end}}
{{template "header" .}}

{{block "content" .}}default content{{end}}