英文:
How to iterate over keys and values of a map in a Go html template
问题
我在go中使用http/template
包有一个模板。如何在模板中同时迭代键和值?
示例代码:
template := `
<html>
<body>
<h1>Test Match</h1>
<ul>
{{range .}}
<li> {{.}} </li>
{{end}}
</ul>
</body>
</html>`
dataMap["SOMETHING"] = 124
dataMap["Something else"] = 125
t, _ := template.Parse(template)
t.Execute(w,dataMap)
在模板中如何访问{{range}}
中的键。
英文:
I have a template in go using the http/template
package. How do I iterate over both the keys and values in the template?
Example code :
template := `
<html>
<body>
<h1>Test Match</h1>
<ul>
{{range .}}
<li> {{.}} </li>
{{end}}
</ul>
</body>
</html>`
dataMap["SOMETHING"] = 124
dataMap["Something else"] = 125
t, _ := template.Parse(template)
t.Execute(w,dataMap)
How do I access the key in {{range}}
in the template
答案1
得分: 7
你可以尝试使用range
来分配两个变量 - 一个用于键,一个用于值。根据这个更改(以及文档),键会按照可能的顺序返回。以下是使用你的数据的示例:
package main
import (
"html/template"
"os"
)
func main() {
// 在这里,我们基本上将map“解包”为键和值
tem := `
<html>
<body>
<h1>Test Match</h1>
<ul>
{{range $k, $v := . }}
<li> {{$k}} : {{$v}} </li>
{{end}}
</ul>
</body>
</html>`
// 创建map并添加一些数据
dataMap := make(map[string]int)
dataMap["something"] = 124
dataMap["Something else"] = 125
// 创建新模板,解析并添加map
t := template.New("My Template")
t, _ = t.Parse(tem)
t.Execute(os.Stdout, dataMap)
}
可能有更好的处理方法,但这在我的(非常简单的)用例中有效
英文:
One thing you could try is using range
to assign two variables - one for the key, one for the value. Per this change (and the docs), the keys are returned in sorted order where possible. Here is an example using your data:
package main
import (
"html/template"
"os"
)
func main() {
// Here we basically 'unpack' the map into a key and a value
tem := `
<html>
<body>
<h1>Test Match</h1>
<ul>
{{range $k, $v := . }}
<li> {{$k}} : {{$v}} </li>
{{end}}
</ul>
</body>
</html>`
// Create the map and add some data
dataMap := make(map[string]int)
dataMap["something"] = 124
dataMap["Something else"] = 125
// Create the new template, parse and add the map
t := template.New("My Template")
t, _ = t.Parse(tem)
t.Execute(os.Stdout, dataMap)
}
There are likely better ways of handling it, but this has worked in my (very simple) use cases
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论