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

GoTemplatesGo Templates

Go Problem Overview


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?

Go Solutions


Solution 1 - Go

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

Solution 2 - Go

A simpler way would be to do: {{.Amap.key1}}. However, this will only work if the key is alphanumeric. If not, you'll need to access it using index.

From the 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKyle BrandtView Question on Stackoverflow
Solution 1 - GoOneOfOneView Answer on Stackoverflow
Solution 2 - GoTarun KhandelwalView Answer on Stackoverflow