Access a map value using a variable key in a Go template

Kyle Brandt picture Kyle Brandt · Oct 2, 2014 · Viewed 51.6k times · Source

How can I look up the value of a map by using a variable key without iterating?

So one can lookup a constant key on variable map $x with $x.key1, but is it possible to do amap.$key?

Answer

OneOfOne picture OneOfOne · Oct 2, 2014

You use the index function:

{{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