How to display an image stored as a page resource when it's an element of an array of objects?

I just posted this on SO here, but then realized this might be the better place to ask:

Images in my front matter are stored like this:

images:
  - image: image_1.jpg
    caption: "image 1 caption"
  - image: image_2.jpg
    caption: "image 2 caption"

I want to display just the first one, so I use the following:

{{ $image := .Resources.GetMatch (printf "**%s" (index .Params.images 0).image) }}

Oddly, this only works if I add the .image part while my local hugo server is running. As soon as I stop and start it again, the site fails to rebuild with the following error:

... execute of template failed: template: partials/content/figure.html:7:70: executing "partials/content/figure.html" at <0>: can't evaluate field image in type string

I just want to be able to access images[0].image. How can I make this work?

{{ with index .Params.images 0 }}
  {{ with $.Resources.Get .image }}
    <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
  {{ end }}
{{ end }}
1 Like

Thanks for the reply! I’m working in a template that does a bunch of other things with $image. Is there some way to get it and store it in the $image variable similarly to how it’s defined above?

get the resource

{{ $i := "" }}
{{ with index .Params.images 0 }}
  {{ $i = $.Resources.Get .image }}
{{ end }}

use the resource

{{ with $i }}
  <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}
1 Like

Or with error checking…

{{ $i := "" }}
{{ with index .Params.images 0 }}
  {{ with $.Resources.Get .image }}
    {{ $i = . }}
  {{ else }}
    {{ errorf "Unable to get resource %q" .image }}
  {{ end }}
{{ end }}

1 Like

I really appreciate the replies.

No matter what I do I continue getting the error executing "partials/content/figure.html" at <.image>: can't evaluate field image in type string.

To provide further assistance I would need to see your repository. Please share it, privately if you wish.

1 Like

Just sent you a private message with the repo address.

It turns out I had some other content types whose front matter still had images in a simple array rather than an array of objects. I finally solved it using @jmooring’s help, like this:

{{ $image := "" }}
{{ if reflect.IsMap (index .Params.images 0) }}
  {{ $image = .Resources.GetMatch (printf "**%s" (index .Params.images 0).image) }}
{{ else }}
  {{ $image = .Resources.GetMatch (printf "**%s" (index .Params.images 0)) }}
{{ end }}

This allows me to have some content types with multiple images and image captions stored as an array of objects in front matter (see OP above), while other content types simply have a single image or an array of images without captions.

Hope others find this useful. Thank you @jmooring!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.