I have a shortcode called debug.html in layouts/shortcodes/debug.html.
{{ with .Resources.ByType "image" }}
{{ range . }}
{{ .RelPermalink }}
{{ end }}
{{ end }}
Note: I have also tried using .Page.Resources.
I have made a subfolder under /content/2020/test, containing an images/ folder and a index.md. In the images folder, I have a PNG file called basketball.png. Within index.md, I have called the shortcode:
{{> debug <}}
However, it returns an error saying: execute of template failed: template: shortcodes/debug.html:1:18: executing "shortcodes/debug.html" at <.Resources.ByType>: can't evaluate field Resources in type *hugolib.ShortcodeWithPage
Do I have to define all page resources in the front matter of index.md before I can use them? Or what is the reason for this error? Thanks.
Ok never mind, I’m stupid. I forgot to name my file index.md and named it test.md instead. Maybe that’s why it couldn’t find the resources. .Page.Resources seems to work (without the ), although it works with the too. Strangely, the appears to be the global context according to the Hugo docs, so would putting the in the shortcode mess up the shortcode’s context (which should be the specific page context?)
Also, what’s the difference between .Resources and .Page.Resources in this context (leaf bundle)?
Yep, I changed it to GetMatch after, the ByType was simply a debugging test because it didn’t work previously. Now if the image is not found, the entire Hugo build fails. Is it possible to wrap the entire shortcode with a fileExists while maintaining the original context?
Sorry about the confusion. Everything works correctly, it’s just that in case I type the “src” attribute wrongly in the shortcode (and the file cannot be found in resources), the entire build will fail. I’m trying to have it output something like “Image could not be found” in the shortcode template instead.
Yes, a with would indeed work, but I heard that with changes the context to within itself, meaning I will not be able to access other shortcodes variables passed in if I do something like:
{{ with (.Page.Resources.GetMatch (printf "**%s*" (.Get "src"))) }}
The context will then simply be the image itself, will it not? I would then not be able to do things like:
{{ with .Get "alt" }}
alt='{{- . -}}'
{{ else }}
alt=''
{{ end }}
Please correct me if I’m understanding the docs wrongly. Thank you!