【问题标题】:Access a map value using a variable key in a Go template使用 Go 模板中的变量键访问映射值
【发布时间】:2014-11-26 22:14:17
【问题描述】:

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

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

【问题讨论】:

    标签: go templates go-templates


    【解决方案1】:

    你使用index函数:

    {{index .Amap "key1"}}
    
    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.
    

    https://golang.org/pkg/text/template#hdr-Functions

    【讨论】:

    • 这在管道内工作吗?你能举个例子说明如何将它用作{{template "name" how_to_index_here?}}的一部分
    • @chakrit:是的,将管道包装在括号中:{{template "name" (index .Amap "key1")}} 应该注意的是,直接从 dot 访问映射键的更简单的语法也可以:{{template "name" .Amap.key1}}
    • 如果结果值是一个结构来选择一个字段,是否也可以? {{index .Amap "key1"}}.Myfield
    • @GertCuykens 在整天搜索该答案但一无所获后,我发现了:{{ with (index .Amap "key1") }}{{ .Myfield }}{{ end }}
    • @JoeLinux,这是一个很好的解决方案。适用于超过字母数字的键,例如{{ with (index .Amap "key-with-hyphens") }} {{ .Myfield }} {{ end }}
    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-01
      • 1970-01-01
      • 2013-10-09
      • 2018-09-21
      • 2015-07-18
      相关资源
      最近更新 更多