英文:
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, &f)
Then I pass it to ExecuteTemplate as follows:
templates.ExecuteTemplate(w, "templates/data.html", map[string]interface{} { "Data": f })
In my template I use this:
<table>
{{range $element := .Data}}
<tr><td>{{$element.Name}}</td><td>{{$element.**Some Field With Spaces**}}</tr>
{{end}}
</table>
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"}}
你好,以下是翻译好的内容:
{{index $element "一些带有空格的字段"}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论