How to get the map value through variables?
The key is stored in the variable.
Example, there is this file: data/images.json
{
"grassland":"/img/grassland.jpg",
"desert":"/img/desert.jpg",
"forest":"/img/forest.jpg",
"snowfield":"/img/snowfield.png",
"ocean":"/img/ocean.png"
}
And then there’s a short code usage is {{< image <image_nane> >}}
I try
{{ $name := (.Get 0) }}
{{ with $name }}
{{ .Site.Data.images[$name] }}
{{ end }}
Report error
bad character U+005B '['
I tried to use inefficient method
{{ $name := (.Get 0) }}
{{ with $name }}
{{ $not_found := true }}
{{ range $k , $v := .Site.Data.images }}
{{ if (and $not_found (eq $k $name)) }}
<img src="{{ $v }}" alt="{{ $name }}">
{{ $not_found = false }}
{{ end }}
{{ print $k "\n"}}
{{ end }}
{{ if $not_found }}
{{ printf "<!-- %s is not foind. -->\n" $name | safeHTML }}
{{ end }}
{{ else }}
{{ print "<!-- Usage: {{< image <image name> >}} -->\n" | safeHTML }}
{{ end }}
It turned out to be a report error
executing "shortcodes/image.html" at <.Site.Data.images>: can't evaluate field Site in type string
In the error message, there is an error in the range statement, so I will test again
{{ range $k , $v := .Site.Data.images }}
<img src="$v" alt="{{ $k }}">
{{ end }}
This can be executed normally. What is the previous error report?
Then, how to index the map value through variables?