Home > Backend Development > Golang > How to Iterate Through a Map in Golang Templates?

How to Iterate Through a Map in Golang Templates?

Barbara Streisand
Release: 2024-11-24 05:49:15
Original
686 people have browsed it

How to Iterate Through a Map in Golang Templates?

Iterating through a Map in Templates

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

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

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!

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