Range <$image.Resize>: nil pointer evaluating resource.Resource.Resize


Noob here, my layout runs through a range of RegularPages and on some of them i have the front matter variable featured_images set to the image location. Then within the range scope i have the following:

{{ printf "%s" .Params.featured_image }}
  {{ with .Params.featured_image }}
    {{ $image := resources.Get . }}
    {{ $image := .Resize "200x200" }}
    <img src="{{ $image.RelPermalink }}">
  {{ end }}

Which is generating the post topic. The printf retuns image paths for the posts that have the front matter variable and %!s(<nil>) for the ones that don’t, so it looks like the .Get (or .GetMatch) is not getting the images even though the with confirms its existence. Do the images need to be at a certain location like resources or assets?

The image is not where you think it is. Your with doesn’t help because it only checks if the parameter contains a value. You’d need something like

{{ $image := resources.Get .Params.featured_image}}
{{ with $image }}
{{ end }}

Yes. If you want to use resources.Get, the images have to be in /assets, as described in the documentation. Alternatively, use page bundles (again: read the documentation on that and use .Resources.GetMatch.

For future questions: Trimmed down information like in your case is often not enough to answer. A sentence like “the front matter variable featured_images set to the image location” doesn’t tell anything unless you say what this image location is. Many people here want you to provide a link to your repository so they can look at the complete site.

1 Like

You need to code defensively for the absence of (a) the front matter parameter, and (b) the image itself.

{{ with .Params.featured_image }}
  {{ with resources.Get . }}
    {{ $alt := path.BaseName .Key | humanize | strings.FirstUpper  }}
    {{ with .Fill "200x200" }}
      <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="{{ $alt }}">
    {{ end }}
  {{ end }}
{{ end }}

Other notes:

  • With the .Resize method, if you specify both width and height, the resulting image will be disproportionally scaled unless the original image has the same aspect ratio. I think you want to use .Fill, .Crop, or maybe .Fit. See documentation.
  • If you name your images something like “white-kitten.jpg”, you can generate the alt attribute based on the filename (e.g., white-kitten.jpg → alt="White kitten").
1 Like

I’m just learning, emacs, orgmode, ox-hugo and hugo, and i suspect that’s where the issue is.
ox-hugo suggests using the static folders to link the images, but for these methods the images need to be in assets or resources folders, might be best to setup this as page bundles. Moved everything into the assets folders and now everything is working properly, will add the extra with line to account for image existence.

Many thanks!

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