Essential Go Text and HTML templates  Suggest an edit

range action

Just as in Go, range can iterate over arrays, slices, maps and channels.

Range over arrays and slices

const tmplStr = `Elements of arrays or slice: {{ range . }}{{ . }} {{end}}
`

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

array := [...]int{3, 8}
err := t.Execute(os.Stdout, array)
if err != nil {
	log.Fatalf("t.Execute() failed with '%s'\n", err)
}

slice := []int{12, 5}
err = t.Execute(os.Stdout, slice)
if err != nil {
	log.Fatalf("t.Execute() failed with '%s'\n", err)
}
Elements of arrays or slice: 3 8 
Elements of arrays or slice: 12 5 

Range over maps

const tmplStr = `Elements of map:
{{ range $k, $v := . }}{{ $k }}: {{ $v }}
{{end}}`

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

data := map[string]int{
	"one":  1,
	"five": 5,
}
err := t.Execute(os.Stdout, data)
if err != nil {
	log.Fatalf("t.Execute() failed with '%s'\n", err)
}
Elements of map:
five: 5
one: 1

Range over channels

const tmplStr = `Elements of a channel: {{ range . }}{{ . }} {{end}}
`

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

ch := make(chan int)
go func() {
	for i := 0; i < 3; i++ {
		ch <- i
	}
	close(ch)
}()
err := t.Execute(os.Stdout, ch)
if err != nil {
	log.Fatalf("t.Execute() failed with '%s'\n", err)
}
Elements of a channel: 0 1 2 
  ↑ ↓ to navigate     ↵ to select     Esc to close