How to get the map value through variables?

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?

2 Likes

Well, that’s using the index function.

{{ index map key }}

But there’s another mistake

executing "shortcodes/image.html" at <.Site.Data.images>: can't evaluate field Site in type string

image.html

{{ $name := .Get 0 }}

{{ with $name }}
  {{ index .Site.Data.image $name }}
{{ end }}

I use this in content files

{{< image ocean >}}

The error seems to be related to the fact that you are rewriting the context with with. The . in .Site is not your project anymore but $name.

You either need to remove the with or access the Site with $.Site.

More here https://regisphilibert.com/blog/2018/02/hugo-the-scope-the-context-and-the-dot/