stihl
stihl

Reputation: 251

iterate Map / Dictionary in golang template

I'm a beginner at Go and am teaching myself some web dev. I'm trying to loop over a map in a template file and cant find any documentation on how to do it. Here is my struct i pass in:

type indexPageStruct struct {
BlogPosts   []post
ArchiveList map[string]int
}

I can loop over BlogPosts just fine using:

{{range .BlogPosts}}
                <article>
                    <h2><a href="/">{{.Title}}</a></h2>
...

But i cant seem to figure out how to do something like :

{{range .ArchiveList}}
                <article>
                    <h2><a href="/">{{.Key}}  {{.Value}}</a></h2>
....

Upvotes: 7

Views: 14880

Answers (1)

icza
icza

Reputation: 418447

You can "range" over a map in templates just like you can "range-loop" over map values in Go. You can also assign the map key and value to a temporary variable during the iteration.

Quoting from package doc of text/template:

If a "range" action initializes a variable, the variable is set to the successive elements of the iteration. Also, a "range" may declare two variables, separated by a comma:

range $index, $element := pipeline

in which case $index and $element are set to the successive values of the array/slice index or map key and element, respectively.

Everything in text/template also applies to html/template.

See this working example:

templ := `{{range $k, $v := .ArchiveList}}Key: {{$k}}, Value: {{$v}}
{{end}}`
t := template.Must(template.New("").Parse(templ))
p := indexPageStruct{
    ArchiveList: map[string]int{"one": 1, "two": 2},
}
if err := t.Execute(os.Stdout, p); err != nil {
    panic(err)
}

Output (try it on the Go Playground):

Key: one, Value: 1
Key: two, Value: 2

Upvotes: 14

Related Questions