Essential Go Text and HTML templates  Suggest an edit

if action

To conditionally render parts of the template, use if action:

const tmplStr = `{{range . -}}
{{if .IsNew}}'{{.Name}}' is new{{else}}'{{.Name}}' is not new{{end}}
{{end}}`

t := template.Must(template.New("if").Parse(tmplStr))

data := []struct {
	Name  string
	IsNew bool
}{
	{"Bridge", false},
	{"Electric battery", true},
}

err := t.Execute(os.Stdout, data)
if err != nil {
	log.Fatalf("t.Execute() failed with '%s'\n", err)
}
'Bridge' is not new
'Electric battery' is new

false values

Templating uses “truthy” logic for deciding what values are true or false in the context of if action:

const tmplStr = `{{range . -}}
{{printf "%- 16s" .Name}} is: {{if .Value}}true{{else}}false{{end}}
{{end}}`

t := template.Must(template.New("if").Parse(tmplStr))

var nilPtr *string = nil
var nilSlice []float32
emptySlice := []int{}

data := []struct {
	Name  string
	Value interface{}
}{
	{"bool false", false},
	{"bool true", true},
	{"integer 0", 0},
	{"integer 1", 1},
	{"float32 0", float32(0)},
	{"float64 NaN", math.NaN},
	{"empty string", ""},
	{"non-empty string", "haha"},
	{"nil slice", nilSlice},
	{"empty slice", emptySlice},
	{"non-empty slice", []int{3}},
	{"nil pointer", nilPtr},
}

err := t.Execute(os.Stdout, data)
if err != nil {
	log.Fatalf("t.Execute() failed with '%s'\n", err)
}
bool false       is: false
bool true        is: true
integer 0        is: false
integer 1        is: true
float32 0        is: false
float64 NaN      is: true
empty string     is: false
non-empty string is: true
nil slice        is: false
empty slice      is: false
non-empty slice  is: true
nil pointer      is: false

Avoid printing empty slices

Truthy logic is useful when we want to show different text if a list of items is empty:

type UserTweets struct {
	User   string
	Tweets []string
}

const tmplStr = `
{{- if not .Tweets -}}
User '{{.User}}' has no tweets.
{{ else -}}
User '{{.User}}' has {{ len .Tweets }} tweets:
{{ range .Tweets -}}
  '{{ . }}'
{{ end }}
{{- end}}`

t := template.Must(template.New("if").Parse(tmplStr))

data := UserTweets{
	User: "kjk",
}
err := t.Execute(os.Stdout, data)
if err != nil {
	log.Fatalf("t.Execute() failed with '%s'\n", err)
}

data = UserTweets{
	User:   "masa",
	Tweets: []string{"tweet one", "tweet two"},
}
err = t.Execute(os.Stdout, data)
if err != nil {
	log.Fatalf("t.Execute() failed with '%s'\n", err)
}
User 'kjk' has no tweets.
User 'masa' has 2 tweets:
'tweet one'
'tweet two'

  ↑ ↓ to navigate     ↵ to select     Esc to close