Home > Backend Development > Golang > How Can I Iterate Through Maps in Go Templates to Group Data?

How Can I Iterate Through Maps in Go Templates to Group Data?

Linda Hamilton
Release: 2024-11-18 07:34:02
Original
870 people have browsed it

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
}
Copy after login

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 }}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template