I am trying to display a list gym classes (Yoga, Pilates etc). For each class type there are several classes, so I want to group all the Yoga classes, and all the Pilates cl
As Herman pointed out, you can get the index and element from each iteration.
{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}
Working example:
package main
import (
"html/template"
"os"
)
type EntetiesClass struct {
Name string
Value int32
}
// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`
func main() {
data := map[string][]EntetiesClass{
"Yoga": {{"Yoga", 15}, {"Yoga", 51}},
"Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
}
t := template.New("t")
t, err := t.Parse(htmlTemplate)
if err != nil {
panic(err)
}
err = t.Execute(os.Stdout, data)
if err != nil {
panic(err)
}
}
Output:
Pilates
3
6
9
Yoga
15
51
Playground: http://play.golang.org/p/4ISxcFKG7v
Check the Variables section in the Go template docs. A range may declare two variables, separated by a comma. The following should work:
{{ range $key, $value := . }}
<li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}