Having trouble implementing image gallery - AKA how to use shortcode in categories.html

Hello, I’m trying to implement this: https://www.control-alt-del.org/posts/building-an-image-gallery-for-hugo/

However I want to use the gallery in theme-name/layouts/partials/widgets/categories.html but I get the error

Process: loading templates: "/themes/theme-name/layouts/partials/widgets/categories.html:1:1": parse failed: template: partials/widgets/categories.html:1: unexpected "<" in command

The shortcode does work under content pages, but I need to use it in the category page.

Shortcodes: extra stuff that is done inside of a Markdown file
Partials: extra stuff that is done inside of a Layout file

You can’t use shortcodes in a layout. Try rewriting the shortcode into a partial and load it from your layout and it might work.

Is there anything to read about how to translate one to the other?

Not really. But I do the following:

  • do whatever is needed in the partial file
  • create a shortcode that calls said partial

This way you change the partial and the shortcodes will update automagically.

But that still depends on the shortcode, which I can’t use in the gallery page. Do you mean the other way around?

Yes, I meant it the other way around. Post the content of your shortcode here and I’ll try to “translate” into my “system”. The final layout file to do the gallery is layouts/partials/the-shortcode.html and layouts/shortcodes/the-shortcode.html only reads the parameters in and uses the partial to show the gallery.

The code is in the site I linked but I’ll paste it here:

<style>
  div.gallery {
     display: flex;
     flex-wrap: wrap;
  }
        div.gallery a {
            flex-grow: 1;
            object-fit: cover;
            margin: 2px;
            display: flex;
        }

        div.gallery a img {            
            height: 200px;
            object-fit: cover;
            flex-grow: 1;
        }

    </style>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.4.0/jquery.fancybox.min.css" />

    <div class="gallery">
        {{ $base := .Get "src" }}
	{{ $path := print "static/" (.Get "src") }}

	{{ range (readDir $path) }}
        {{- $thumbext := "-thumb" }}
        {{- $isthumb := .Name | findRE ($thumbext | printf "%s\\.") }}<!-- is the current file a thumbnail image? -->
        {{- $isimg := lower .Name | findRE "\\.(gif|jpg|jpeg|tiff|png|bmp)" }}<!-- is the current file an image? -->
        {{- if and $isimg (not $isthumb) }}
        {{- $thumb := .Name | replaceRE "(\\.)" ($thumbext | printf "%s.") }}
            <a data-fancybox="gallery" href="/{{ $base }}/{{ .Name }}">
                <img src="/{{ $base  }}/{{ $thumb }}">  <br/>            
            </a>
        {{- end }}
	{{ end }}
    </div>