.Site.GetPage function doesn't work in range block

I am trying to create a carousel slider on my homepage that use existing webp images from some of my leaf bundles. I also want to have Hugo process these images to create a jpeg fallback. Here is what I have in my code:


title = "Website"

  src =  "path/to/bundle/some-image.webp"
  alt = "Some Image"

  src =  "path/to/another/bundle/some-other-image.webp"
  alt = "Some Other Image"

  src =  "path/to/yet/another/bundle/yet-another-image.webp"
  alt = "Yet Another Image"


{{ range .Params.slides -}}
{{ $path := path.Split .src }}
{{ $page := .Site.GetPage $path.Dir }}
{{ $img := $page.Resources.GetMatch $path.File }}
<div class="swiper-slide">
      <source srcset="{{ $img.RelPermalink }}" type="image/webp">
      <source srcset="{{ $img.Resize "1080x jpg" }}" type="image/jpeg">
      <img src="{{ $img.Resize "1080x jpg" }}" alt="{{ .alt }}" />
{{ end -}}

Each of the leaf bundles that hold the images have an index.md with the title defined in the front matter and the images sitting next to them in the same directory.

Unfortunately none of this works. After good while of trial and error, I discovered that the reason it is not working is because .Site.GetPage doesn’t return anything when called inside a range block. If .Site.GetPage isn’t supposed to work inside of a range block, shouldn’t this throw an error?

Anyways, I would like some help to get this working or even suggestions on a better way to do this.

hugo version
hugo v0.83.1-5AFE0A57+extended windows/amd64 BuildDate=2021-05-02T14:38:05Z VendorInfo=gohugoio

I’m pretty sure it does. That said, you have a “dot context” issue with your code (there are great articles written about this), but to cut a long story short, if you use site.GetPage instead, that will work.

1 Like

Thanks bep! Changing that part of the line to site.GetPage (path.Join $path.Dir "index") as well as wrapping $img.Resize "1080x jpg" with ().RelPermalink fixed the code for me. So basically, I now have:

  <source srcset="{{ $img.RelPermalink }}" type="image/webp">
  {{ $jpegURL := ($img.Resize "1080x jpg").RelPermalink }}
  <source srcset="{{ $jpegURL }}" type="image/jpeg">
  <img src="{{ $jpegURL }}" alt="{{ .alt }}" />

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