Search code examples
gogo-html-template

How to iterate over keys and values of a map in a Go html template


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


Solution

  • 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 :)