Iterating through a Map in a Go Template
When working with maps in Go templates, it's essential to understand how to iterate over their elements.
func groupClasses(classes []entities.Class) map[string][]entities.Class { classMap := make(map[string][]entities.Class) for _, class := range classes { classMap[class.ClassType.Name] = append(classMap[class.ClassType.Name], class) } return classMap }
To iterate through the classMap generated by the groupClasses function in a template, follow these steps:
Range Iteration: To iterate through a map, use the following syntax:
{{ range $key, $value := . }}
where:
For example, to list out all class types and their corresponding classes:
{{ range $key, $value := . }} <li><strong>{{ $key }}</strong>: {{ $value }}</li> {{ end }}
This will generate HTML like:
<li><strong>Yoga</strong>: [Yoga class 1, Yoga class 2, ...]</li> <li><strong>Pilates</strong>: [Pilates class 1, Pilates class 2, ...]</li>
The above is the detailed content of How Do I Iterate Through a Map in a Go Template?. For more information, please follow other related articles on the PHP Chinese website!