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

时间:2014-10-01 23:05:41

标签: templates go

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

因此可以使用$x.key1在变量地图$ x上查找常量键,但可以amap.$key吗?

2 个答案:

答案 0 :(得分:77)

您使用index功能:

{{index .Amap "key1"}}

来自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.

答案 1 :(得分:2)

更简单的方法是:{{.Amap.key1}}。但是,这仅在键为字母数字键时才有效。如果没有,则需要使用index来访问它。

来自documentation

- 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