Home > Backend Development > Golang > How can I iterate through a map in a Go template?

How can I iterate through a map in a Go template?

Barbara Streisand
Release: 2024-11-29 05:00:10
Original
766 people have browsed it

How can I iterate through a map in a Go template?

Iterating Through a Map in a Template

In your code, you have created a function, groupClasses, that converts a slice of classes into a map, where the keys are class types (e.g., "Yoga", "Pilates") and the values are slices of classes of that type.

To iterate through this map in your template, you can use the range keyword with two variables, as explained in the Variables section of the Go template documentation. Here's an example:

{{ range $classType, $classes := . }}
    <li><strong>{{ $classType }}</strong>: {{ range $class := $classes }} {{ $class.Name }} {{ end }}</li>
{{ end }}
Copy after login

This template will iterate through the map, assigning the class type to the variable $classType and the slice of classes to the variable $classes for each iteration. Within the loop, it lists the classes for each class type.

By using two variables, you can access both the key and the value of the map item during the iteration. This allows you to display the data in a meaningful way in your template.

The above is the detailed content of How can 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