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
Linda HamiltonOriginal
2024-11-18 07:34:02882browse

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!

Statement:
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