Hugo Subscript and Superscript Shortcodes


In its current avatar, there’s no way to get superscript or subscript text in your Hugo content without directly embedding <sup> or <sub> tags in your posts and setting unsafe: true in the Goldmark renderer settings in config.yaml. A cleaner alternative is to use shortcodes to embed these tags in the content. This keeps us from having to enable HTML tags in all posts, and we can have our Markdown content files looking mostly clean.

Hugo Shortcodes are small snippets that can be put inside the content files that can call built-in or custom templates to render content. We will be creating two custom shortcodes here, and use a positional parameter as they are simple to define and use. Our use case is extremely simple as we will have just one parameter which will contain the text to render as subscript or superscript.

Create a file /layouts/shortcodes/sub.html -

<sub>{{ .Get 0 | markdownify }}</sub>

.Get 0 fetches the first parameter and parses it into Markdown using markdownify. The whole thing is encapsulated in <sub> tags so that it is rendered in subscript.

This shortcode is used in content files like this -

This is an example of {{< sub "subscript" >}} text

Which produces -

This is an example of subscript text

Similarly, we can create a /layouts/shortcodes/super.html with -

<sup>{{ .Get 0 | markdownify }}</sup>

And get superscript text by using the super shortcode -

E = mc{{< super "__gazillion__ squared" >}}

Resulting in E = mcgazillion squared

Neat, isn’t it?

Note that the name of the shortcode file (“super”.html) corresponds to the shortcode name ({{< super "something" >}}).