5

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 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.