How can I use value of a variable to reference to another variable in a Go template?
template:
Hello, {{ index $.planet }}!
data:
{
"planet": "neptune",
"planet_field": "planet"
}
I need to use planet_field
instead of planet
in my template, and have neptune
printed.
note: i cant change my data structure, the use case is for Prometheus alert templates that only get data by labels.
I'm testing on this website: gotemplate.io (copy/paste the template/data above into that site).
The value of the planet
variable can be referenced through planet_field
using the index
function as follows:
Hello, {{ index . .planet_field }}!
The index
function is a Go template function that retrieves the value from a map/slice using its key or index. index . .planet_field
looks up the value of the planet
key in the data map, which is neptune
.
For more details on the index
function, please see https://pkg.go.dev/text/template