在golang模板中迭代Map / Dictionary

6

我是Go语言的初学者,正在自学一些Web开发技术。我试图在模板文件中循环遍历一个Map,但没有找到任何关于如何实现的文档。这是我传递进去的结构体:

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

我可以使用以下代码轻松循环遍历BlogPosts:

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

但我似乎无法弄清楚如何做类似于以下的事情:
{{range .ArchiveList}}
                <article>
                    <h2><a href="/">{{.Key}}  {{.Value}}</a></h2>
....
1个回答

13
您可以像在Go中“range-loop”映射值一样,在模板中“range”映射。在迭代期间,您还可以将映射键和值分配给临时变量。引用自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.

text/template中的所有内容都同样适用于html/template

查看此工作示例:

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)
}

输出结果(在Go Playground上试一试):

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接