“无法评估类型界面中的字段键”访问Go模板中的键

问题描述 投票:-2回答:1

我的模板:

<!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是map[string]interface{}形式的JSON

Reproducible example

go go-templates
1个回答
1
投票

似乎您的范围函数是错误的。我检查了this answer并相应地更新了您的代码。有效。这是playground link

© www.soinside.com 2019 - 2024. All rights reserved.