Hugo Shortcode For Custom Image Handling

On my generously sized list of improvements I need to make to this site are a couple of image handling items. I crossed off one of those today, after going down a Rabbit Hole while writing another post that I intended to publish today instead of this one.

Up until now, when I’ve put a screenshot image in a post on this site, I’ve just linked to it directly, which causes a couple issues. First, there’s the image sizing issue – screenshots are high resolution and so appear massive when just linked to inline like that. Second, alignment preferences and captioning can be an issue.

Hugo does have a figure shortcode, but as far as I can tell, it doesn’t have any way to set the image alignment. It does support setting a css class for the figure, but I couldn’t find a way using css to actually affect my image alignment when using the Hugo figure shortcode.

So I wrote my own. It’s very simple.

I call it “img.html”, and it looks like this:

{{ with .Get "align" }}<div style="text-align: {{.}};">{{ end }}
<figure {{ with .Get "class" }}class="{{.}}"{{ end }}>
    {{ with .Get "link"}}<a href="{{.}}">{{ end }}
        <img src="{{ .Get "src" }}"{{ with .Get "width"}} width="{{.}}"{{ end }} />
    {{ if .Get "link"}}</a>{{ end }}
    {{ with .Get "caption" }}<figcaption><small><i>{{.}}</i></small></figcaption>{{ end }}
</figure>
{{ if .Get "align" }}</div>{{ end }}

Its main features are that it accepts the following parameters:

  • src, for image source,
  • link, for any URL the image may link to,
  • align, so I can easily set a quick and dirty center alignment, for example,
  • class, if I want to include a css class,
  • caption, which I display in small italic text under the image, if I choose to supply one.

For example:

{{< img src="/images/rsslink.jpg" caption="Hugo page header RSS link" width="500" link="/images/rsslink.jpg" align="center" >}}

You can see this exact call to the img shortcode in my post about adding feed links to your page headers with Hugo.

It doesn’t actually do much that the Hugo figure shortcode doesn’t do, and it doesn’t do several things that the Hugo shortcode does do, but I can control the image alignment. And, obviously, I can add more features over time as needed.

When in doubt, throw together a shortcode and behold the beauty of Hugo shortcodes and parameter passing.