Shortcode can’t evaluate field Resources in type *hugolib.ShortcodeWithPage

Hi, im new to Hugo. Ive setup a clean Hugo project, with one Blog entry, as described in the Hugo QuickStart manual.

I created a blog entry bundle, like so:

  • /blog/my-first-post/index.md
  • /blog/my-first-post/images/carousel/image1.jpeg
  • /blog/my-first-post/images/carousel/image2.jpeg
  • /blog/my-first-post/images/carousel/image3.jpeg

And a simple Shortcode:

  • /layouts/shortcodes/test.html

with…

{{ $images := .Resources.Match "images/carousel/*" }}

{{ range $images }}
<img src="{{ .RelPermalink }}" alt="" class="img-fluid pb-3">
{{ end }}

I use the Shortcode in the blog post index.md, like so

{{< test >}}

My idea was to show the pictures in the subdirectory of the bundle.

Running that stuff, I get an Error:

"test": failed to process shortcode: "/layouts/shortcodes/test.html:1:24": execute of template failed at <.Resources.Match>: can’t evaluate field Resources in type *hugolib.ShortcodeWithPage

It does not matter where the images are located (in the root directory of the bundle, in the ‘images’ directory, or in the subdirectory as specified above. The result is always the same. It seems that it does not know the .Resources object at all.

I have looked at many examples where similar code ran. Why doesn’t it work in my case? Any Ideas welcome.

hugo version is 0.121.1

should be

{{ $images := .Page.Resources.Match "images/carousel/*" }}
1 Like

Okay, that fixed it for me. Great! I’ve looked at a lot of code, and often just .Resources.Match is used, and seems to work. In what context is this used? Where is the difference?

Each template receives context (the dot). You can think of context as an object with values/methods. The context varies by template type, page kind, content, etc.

Shortcode templates receive the following context:
https://gohugo.io/quick-reference/methods/#shortcode

1 Like

Thanks that clarifies a lot.

1 Like

My Carousel now works great in the Blog Pages, but I want to use it also in the Main index page _index.md, but it cannot find the images again,

  • neither in the global /asset/ folder,
  • nor in the subdirectory /images/ relative to _index.md.

what works:

  • Simply embedding the image with [...](...) works, no matter which folder.
  • placing the images next to the _index.md also works.

I would also like to store the images in a structured way in subdirectories (as in the blog). Why is this possible in the blog, but not in _index.md?

See https://gohugo.io/content-management/page-bundles/.

With branch bundles (directories with an _index.md file) the resources must be adjacent to the _index.md file, not beneath it.

This restriction will be lifted if #11439 is implemented.

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