Iterating through map in template
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 }}
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