patterngoCritical
Access a map value using a variable key in a Go template
Viewed 0 times
keyaccessusingvariabletemplatevaluemap
Problem
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
So one can lookup a constant key on variable map $x with
$x.key1, but is it possible to do amap.$key?Solution
You use the
https://golang.org/pkg/text/template#hdr-Functions
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
Code Snippets
{{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.Context
Stack Overflow Q#26152088, score: 215
Revisions (0)
No revisions yet.