How to store thumbnail images in page bundle folder for Hugo sites with Mainroad theme
Keeping all page-related content in one folder...
For quite a time I’ve been bugged with this annoyance to put thumbnail images of the pages into static directory. Thats for Mainroad, Rodster and similar Hugo themes.
I like to organise Hugo page content as page bundles, and would rather prefer if all page-related images are stored inside this page bundle.
And here I’m presenting you a solution!
How to keep Mainroad Hugo Theme (and similar) thumbnail images in Page Bundle folder
Just put this text to the file ./layouts/partials/post_thumbnail.html, and you can store your image anywhere from bundle and static folder :).
{{- if $thumbnail := .page.Params.thumbnail }}
{{- $class := .class }}
{{- $visibility := .page.Site.Params.thumbnail.visibility | default (slice "list" "post") }}
{{- $valueType := printf "%T" $thumbnail -}}
{{- $isMap := in $valueType "map" -}}
{{- if $isMap }}
{{ $visibility = default (slice "list" "post") (default .page.Site.Params.thumbnail.visibility $thumbnail.visibility) }}
{{ $thumbnail = $thumbnail.src }}
{{- end }}
{{- if in $visibility $class }}
{{- $thumbnailURL := "" }}
{{- /* Try to find image as a page resource first (for bundle pages) */ -}}
{{- $resource := .page.Resources.GetMatch $thumbnail }}
{{- if $resource }}
{{- $thumbnailURL = $resource.RelPermalink }}
{{- else }}
{{- /* Fallback to static folder image using relURL */ -}}
{{- $thumbnailURL = $thumbnail | relURL }}
{{- end }}
<figure class="{{ with $class }}{{ . }}__thumbnail {{ end }}thumbnail">
{{ if eq $class "list" }}<a class="thumbnail__link" href="{{ .page.RelPermalink }}">{{ end }}
<img class="thumbnail__image" src="{{ $thumbnailURL }}" alt="{{ .page.Title }}">
{{ if eq $class "list" }}</a>{{ end }}
</figure>
{{- end }}
{{- end }}
As you see from the comments this nice bit of template is trying to generate image ref to the one stored in the page bundle, and if image is not found - it falls back to the default - static folder. So it’s backwards compatible!
Enjoy!
Happy hugoing!