Here’s a custom Hugo shortcode that creates an image gallery in a masonry style using GLightbox. This approach will display images from a specified folder in a masonry layout, and each image will open in a lightbox when clicked.
This website is built with Hugo, a static site generator that uses Markdown for writing content files. Markdown allows you to insert images with the following syntax:
![alt text](/path/to/image.jpg)
However, this syntax has some drawbacks, such as not being able to add a title, a caption, or a link to the image. To solve this problem, you can create a custom Hugo shortcode that lets you display the additional details of the image, such as its title or link.
Please note that, this post is assuming that you know how to make a blog in Hugo and what is shortcodes in Hugo.
Custom Image Shortcode
Below is the Shortcode for the displaying the image in the Markdown with required attributes and you can see the rendered ouput also.
Image with Caption and link
{{/* < figure src="/path/to/image.jpg"
alt="Tree of Life Photo by Bino"
link="https://binovarghese.com/"
title="Tree of Life / Bahrain"
attr="Photo by Bino"
attrlink="https://binovarghese.com/" > */}}
Output
Image with Caption only
{{/* < figure src="/path/to/image.jpg"
alt="Athar Monument in Bahrain / Photo by Bino"
title="Photo by Bino" > */}}
Output
Below is the code for above custom shortcode.
figure.html
<figure {{ with .Get "class" }}class="{{ . }}"{{ end }}>
{{ with .Get "link" }}<a href="{{ . }}" >{{ end }}
<img class="rounded" src="{{ .Get "src" }}" {{ if or (.Get "alt") (.Get "caption") }}alt="{{ with .Get "alt" }}{{ . }}{{ else }}{{ .Get "caption" }}{{ end }}"{{ end }} />
{{ if .Get "link" }}</a>{{ end }}
{{ if or (or (.Get "title") (.Get "caption")) (.Get "attr") }}
<figcaption class="text-center">
{{ if isset .Params "title" }}
<h5>{{ .Get "title" }}</h5>{{ end }}
{{ if or (.Get "caption") (.Get "attr") }}
<p class="mt-0">
{{ .Get "caption" }}
{{ with .Get "attrlink" }}<a href="{{ . }}"> {{ end }}
{{ .Get "attr" }}
{{ if .Get "attrlink" }}</a> {{ end }}
</p> {{ end }}
</figcaption>
{{ end }}
</figure>
You can put the above HTML file in the shortcodes folder under the layouts folder and please note it will replace the built-in figure shortcode in the Hugo.
If you want, you can modify the shortcode as per your requirments to add more details. The style classes in the components are from Bootstrap, but you can use as per you preferences.
For exploring more, you can checkout the Card shortcode here.
What are your thoughts on this post?
I’d love to hear from you! Click this link to email me—I reply to every message!
Also use the share button below if you liked this post. It makes me smile, when I see it.