Home >Backend Development >Golang >How Can I Iterate Through Maps in Go Templates to Group Data?
Iterating Through Maps in Templates
In Go templates, one commonly encounters the need to iterate through a map. This can be challenging due to the template language's inherent properties.
Objective: Display a list of gym classes grouped by class type (e.g., Yoga, Pilates).
Solution: Utilize a function like groupClasses() to create a map of class types to classes:
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 }
Iterating through the Map:
The challenge lies in iterating through the map in the template. According to the Go template docs, you need to access it in the .Key format. To unpack it, you can declare two variables separated by a comma in the range:
{{ range $key, $value := . }} <li><strong>{{ $key }}</strong>: {{ $value }}</li> {{ end }}
This will iterate through the map, accessing both the key (class type) and the value (list of classes). You can now display the data as needed.
The above is the detailed content of How Can I Iterate Through Maps in Go Templates to Group Data?. For more information, please follow other related articles on the PHP Chinese website!