-2

My template:

<!DOCTYPE html><html><head><title>{{ .title }}</title><link rel="stylesheet" href="/stylesheets/style.css"/></head><body><p>New Id On My Website</p><table><tbody>{{/* key, val */}}{{ range .lead }}<tr><td><strong>{{ .key }}</strong></td><td>{{ .val }}</td></tr>{{ end }}</tbody></table></body></html>

This is my data.

 {
    "lead": {
          "MOBILE": "1212121212121"
      },
     "title" : "New ID"
    }

If I execute this template with the data, it gives the following error.

template: tmpl:1:222: executing "tmpl" at <.key>: can't evaluate field key in type interface {}

My code :

var tmplBytes bytes.Buffer
err = tmpl.Execute(&tmplBytes, vars)
if err != nil {
    panic(err)
}

Here vars is the JSON in the form of map[string]interface{}

Reproducible example

E_net4
  • 27,810
  • 13
  • 101
  • 139
Pardha.Saradhi
  • 468
  • 1
  • 10
  • 27

1 Answers1

2

It looks like your range function is wrong. I checked this answer and updated your code accordingly. It worked. Here is the playground link.

The only difference is , I updated your range template to:

<tbody>
{{ range $key,$value := .lead }}
<tr><td><strong>{{ $key }}</strong></td>
<td>{{ $value }}</td></tr>
{{ end }}
</tbody>
atakanyenel
  • 1,367
  • 1
  • 15
  • 20