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

Barbara Streisand
Release: 2024-11-23 04:44:13
Original
288 people have browsed it

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

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

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

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

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!

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