Question:
I have a function that groups gym classes into a map based on class type. How can I iterate through this map in a Golang template?
Answer:
The Go template docs recommend the following pattern when iterating through a map:
{{ range $key, $value := . }} <li><strong>{{ $key }}</strong>: {{ $value }}</li> {{ end }}
This syntax declares two variables, separated by a comma: $key for the map keys and $value for the map values. The range operator then iterates over the map, assigning the key and value to these variables on each iteration.
Using this approach, you can iterate over your mapped class groups and display the class types and the associated classes in your template. For example:
{{ range $classType, $classes := . }} <h3>{{ $classType }}</h3> <ul> {{ range $class := $classes }} <li>{{ $class.Name }}</li> {{ end }} </ul> {{ end }}
The above is the detailed content of How to Iterate Through a Map in Golang Templates?. For more information, please follow other related articles on the PHP Chinese website!