Home >Backend Development >Golang >How Do I Iterate Through a Map in a Go Template?

How Do I Iterate Through a Map in a Go Template?

Barbara Streisand
Barbara StreisandOriginal
2024-11-23 04:44:13377browse

How Do I Iterate Through a Map in a Go Template?

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:

  1. Understand Key-Value Variables: In Go templates, range iterations can declare multiple variables separated by commas.
  2. Range Iteration: To iterate through a map, use the following syntax:

    {{ range $key, $value := . }}
    

where:

  • $key represents the map key (e.g., the class type name)
  • $value represents the map value (e.g., the slice of classes for that type)
  1. Access Elements: Within the range block, you can access the key and value using the $key and $value variables.

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!

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