Home >Backend Development >Golang >How to Iterate Through a ClassType-based Map in Go Templates?
When displaying a list of gym classes grouped by class type, an efficient solution is to create a map that associates each class type with its corresponding classes. However, to display this structured data effectively in a template, it's important to understand how to iterate through the map correctly.
In this case, we have a map classMap where the keys are class type names and the values are slices of classes corresponding to that type. To iterate through this map and display the data, we can leverage the Variables section of the Go template docs, which allows us to declare two variables for each iteration using a comma-separated syntax.
The following template code demonstrates how to iterate through the classMap and display the class type names (keys) and the corresponding slices of classes (values):
{{ range $key, $value := . }} <li><strong>{{ $key }}</strong>: {{ $value }}</li> {{ end }}
In this template, the $key variable represents the class type name, and the $value variable represents the corresponding slice of classes for that type. This allows us to easily access and display both the class type names and the associated classes within the HTML markup.
The above is the detailed content of How to Iterate Through a ClassType-based Map in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!