在模板中访问包含空格的字段。

huangapple go评论87阅读模式
英文:

Access a field containing a space in a template

问题

我正在尝试弄清楚如何在Go语言中访问包含空格的模板中的地图字段。但是我似乎无法解决这个问题。

我已经从另一个我无法控制的来源解码了一个JSON数组,代码如下:

var f []interface{}
json.Unmarshal(externalData, &f)

然后我将其传递给ExecuteTemplate,代码如下:

templates.ExecuteTemplate(w, "templates/data.html", map[string]interface{}{"Data": f})

在我的模板中,我使用了以下代码:

<table>
{{range $element := .Data}}
<tr><td>{{$element.Name}}</td><td>{{$element.**Some Field With Spaces**}}</tr>
{{end}}
</table>

问题就出在这里。我猜我可以通过在将数据发送到模板之前手动重命名"Some Field With Spaces"键来解决这个问题,但我希望保持原样。我想我也可以创建一个模板函数来返回正确的键名,但这似乎不是一个很好的解决方案。

英文:

I am trying to figure out how I can access a map field in a template that contains a space in Go. But I can't seem to figure this out..

I have decoded a JSON array from another source that I don't control like so:

var f []interface{}
json.Unmarshal(externalData, &amp;f)

Then I pass it to ExecuteTemplate as follows:

templates.ExecuteTemplate(w, &quot;templates/data.html&quot;, map[string]interface{} { &quot;Data&quot;: f })

In my template I use this:

&lt;table&gt;
{{range $element := .Data}}
&lt;tr&gt;&lt;td&gt;{{$element.Name}}&lt;/td&gt;&lt;td&gt;{{$element.**Some Field With Spaces**}}&lt;/tr&gt;
{{end}}
&lt;/table&gt;

And that is where it goes wrong. I guess I can solve this by renaming the "Some Field With Spaces" key manually before sending the data to the template but I'd like to keep it as is. I figure I could probably also make a template function that returns the right key name but that doesn't seem like a very good solution.

答案1

得分: 1

{{index $element "some field with spaces"}}

playground example

你好,以下是翻译好的内容:

{{index $element "一些带有空格的字段"}}

playground 示例

英文:
{{index $element &quot;some field with spaces&quot;}}

playground example

huangapple
  • 本文由 发表于 2014年10月29日 04:20:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/26617774.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定