if action

suggest change

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

main.go

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)
	}

Output:

'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:

main.go

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)
	}

Output:

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:

main.go

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)
	}

Output:

User 'kjk' has no tweets.
User 'masa' has 2 tweets:
'tweet one'
'tweet two'

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents