she*_*eki 5 go go-html-template
我有一个模板使用该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)
Run Code Online (Sandbox Code Playgroud)
如何访问{{range}}模板中的键
您可以尝试的一件事是使用range分配两个变量 - 一个用于键,一个用于值.根据此更改(和文档),密钥将在可能的情况下按排序顺序返回.以下是使用您的数据的示例:
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)
}
Run Code Online (Sandbox Code Playgroud)
可能有更好的方法来处理它,但这在我的(非常简单的)用例中起作用:)