When first trying Hugo, I thought shortcode was the same as partial where I can call it from a template but I was wrong. A shortcode will not work in a template file (.html file) but inside a content file (.md file). It is a simple snippet that Hugo will render using a predefined template.

Why using shortcodes?

Hugo uses markdown for its contents. But let’s say we want to post something richer like adding a video or image gallery to a post. How do we do that? Putting raw HTML to a markdown content contradicts the simplicity of Markdown’s syntax. We would want to make our markdown contents as clean as possible. That’s why Hugo created shortcodes.

Built-in and custom shortcodes

There are a set of built-in shortcodes in Hugo for common usages, such as figure for displaying image, gist for displaying GitHub gist, highlight for highlighting text, etc.

There are also for pre-defined shortcodes for displaying social media post from Instagram, Twitter, Youtube, and Vimeo.

Of course, there are cases that can’t be cover by Hugo’s built-in shortcodes, but we can create our custom shortcodes easily in Hugo.

Following is a result of my experiment displaying images in a post using a custom shortcode. The images below are from my sunset-instagram-photos. Hover to see the effect and click on the image to see it on Instagram.

Here are example code snippets for image gallery above.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<div class="row no-gutters">
    {{ range .Params }}
    <div class="col-4">
        <figure class="hovereffect">
            <a href="https://www.instagram.com/p/{{ . }}" target="_blank">
                <img src="https://www.instagram.com/p/{{ . }}/media/?size=t" alt="{{ . }}" 
                    class="img-gallery img-thumbnail">
            </a>
        </figure>
    </div>
    {{ end }}
</div>

Then, call the shortcode from a markdown page

1{{< image-gallery Bl-t7CsHuUv Bl-geArH1SN BlxiyTrnNY7 BimHyMCHBPu BpZ3DZChqri Bjb6RW5nc8E BiiYGCin1ti BfR9ZQTn0zZ Be-rinun40n >}}