使用Go模板中的变量键访问地图值

Kyl*_*ndt 57 templates go

如何在不迭代的情况下使用变量键查找地图的值?

因此,可以在变量映射$ x上查找常量键$x.key1,但是可以amap.$key吗?

One*_*One 95

你使用的index功能:

{{index .Amap "key1"}}
Run Code Online (Sandbox Code Playgroud)

来自http://golang.org/pkg/text/template/:

index
    Returns the result of indexing its first argument by the
    following arguments. Thus "index x 1 2 3" is, in Go syntax,
    x[1][2][3]. Each indexed item must be a map, slice, or array.
Run Code Online (Sandbox Code Playgroud)

  • @GertCuykens在整天搜索到完全答案并且没有任何结果之后,这就是我想到的:```{{with(index .Amap"key1")}} {{.Myfield}} {{end}} ``` (10认同)
  • @chakrit:是的,用parens包装管道:`{{template"name"(index .Amap"key1")}}`应该注意的是,直接从dot访问地图键的更简单的语法也可以:`{{ template"name".Amap.key1}}` (3认同)
  • 如果结果值是选择字段的结构,是否也有可能?`{{index .Amap "key1"}}.Myfield` (2认同)
  • @JoeLinux,这是一个很好的解决方案。适用于多于字母数字的键,例如 `{{ with (index .Amap "key-with-hyphens") }} {{ .Myfield }} {{ end }}` (2认同)

小智 7

更简单的方法是做:{{.Amap.key1}}。但是,这仅在密钥是字母数字时才有效。如果没有,您需要使用index.

文档

- The name of a key of the data, which must be a map, preceded
  by a period, such as
    .Key
  The result is the map element value indexed by the key.
  Key invocations may be chained and combined with fields to any
  depth:
    .Field1.Key1.Field2.Key2
  Although the key must be an alphanumeric identifier, unlike with
  field names they do not need to start with an upper case letter.
  Keys can also be evaluated on variables, including chaining:
    $x.key1.key2
Run Code Online (Sandbox Code Playgroud)