"can't evaluate field key in type interface" 在 Go 模板中访问键

"can't evaluate field key in type interface" accessing Keys in Go 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>

这是我的数据。

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

如果我用数据执行这个模板,它会给出以下错误。

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

我的代码:

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

这里的vars就是JSON的形式map[string]interface{}

Reproducible example

看来你的范围函数是错误的。我检查了 this answer and updated your code accordingly. It worked. Here is the playground link

唯一不同的是,我将您的范围模板更新为:

<tbody>
{{ range $key,$value := .lead }}
<tr><td><strong>{{ $key }}</strong></td>
<td>{{ $value }}</td></tr>
{{ end }}
</tbody>