如何在Go html模板中迭代地图的键和值

时间:2013-07-15 15:58:02

标签: 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)

如何访问模板

{{range}}中的密钥

1 个答案:

答案 0 :(得分:7)

您可以尝试的一件事是使用range分配两个变量 - 一个用于键,一个用于值。每this次更改(以及docs),密钥将按可能的顺序返回。以下是使用您的数据的示例:

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

可能有更好的方法来处理它,但这在我的(非常简单的)用例中有效:)

相关问题