简体   繁体   中英

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>
....

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM