如何打印包含点的键的值 [英] How to print the value of a key containing dots
问题描述
我试图打印一个地图的值,它的关键点上有一个点(。
)。
示例映射:
type TemplateData struct {
数据映射[string] int
}
tpldata:= TemplateData {map [string] int {core.value:1}}
{{$ key:=core.value}}
{ {.Data.key}}
但是:
2014/06/17 16:46:17 http:panic serving [:: 1]:41395:template:template.html:13:bad character U + 0024'$ '
和
{{.Data。core.value}}
但是:
2014/06/17 16:45:07 http:panic serving [:: 1]:41393:template:template.html :12:错误的字符U + 0022'''
请注意,我能够成功打印没有点的键值。
希望标准库已经提供了函数 index
( http:// golang。 org / pkg / text / template /#hdr-Functions ),它将完成Martin的 dotNotation
函数的功能。
使用它只需写:
{{index .Datacore.value}}
在大小写的情况下, index
函数将返回一个默认值钥匙不存在。如果你的字典具有同类数据,这将起作用,但是当它是异构的时它会返回错误的值。在这种情况下,您可以显式设置默认值:
{{0 |或(index .Datacore.value)}}
I'm trying to print the values of a map, whose keys have a dot (.
) on it.
Example map:
type TemplateData struct {
Data map[string] int
}
tpldata := TemplateData{map[string]int {"core.value": 1}}
I've tried:
{{ $key := "core.value" }}
{{ .Data.key }}
but got:
2014/06/17 16:46:17 http: panic serving [::1]:41395: template: template.html:13: bad character U+0024 '$'
and
{{ .Data."core.value" }}
but got:
2014/06/17 16:45:07 http: panic serving [::1]:41393: template: template.html:12: bad character U+0022 '"'
Note that I'm able to successfully print the value of keys without dots.
As @martin-ghallager said, one needs to use an external function to access those elements.
Hopefully the standard library already provides the function index
(http://golang.org/pkg/text/template/#hdr-Functions), which will do exactly what Martin's dotNotation
function does.
To use it just write:
{{ index .Data "core.value" }}
The index
function will return a default value in case the key is not present. This works if your dictionary has homogeneous data, however it will return the wrong value when it is heterogeneous. In such a case you can explicitly set the default with:
{{ 0 | or (index .Data "core.value") }}
这篇关于如何打印包含点的键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!