Hugo image shortcode

Image Gallery Shortcode

Curious about creating an image gallery shortcode in Hugo? Click here to learn more.

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

Tree of Life Photo by Bino

Tree of Life / Bahrain

Photo by Bino

Image with Caption only

{{/* < figure src="/path/to/image.jpg" 
alt="Athar Monument in Bahrain / Photo by Bino" 
title="Photo by Bino" > */}}

Output

Bahrain Athar Photo by Bino

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.

Read More