In our previous post, we took a look at Hugo shortcodes which are HTML snippets that you can use as a way to extend the html that is generated by Hugo. There are several shortcodes built-in to Hugo but you can also easily create your own custom shortcodes. In this post, we are going to take a look at how to create our own shortcode.

To create a shortcode you need to create a file in thr layouts\shortcodes folder.

Consider the file name carefully since the shortcode name will mirror be that of the file but without the .html extension. For example, layouts/shortcodes/myshortcode.html will be called with either {{< myshortcode >}} or {{% myshortcode %}} depending on the type of parameters you choose.

Shortcodes can also take parameters either as positional or named parameters.

Create Our Custom Shortcode

Let’s build a bootstrap alert shortcode.

What We Are Building:

example alert shortcode

Create Alert Shortcode:

  1. Create layouts\shortcodes\alert.html

  2. Add the following to alert.html

    <div
        class=“alert alert-{{ with .Get “class” }}{{.}}{{end}}”
        role="alert">{{ .Inner | markdownify }}</div>
    

The above shortcode uses named parameters to get the class to use (success, info, warning and danger) {{ with .Get "class" }}{{.}}{{ end }} and then grabs that inner contents of between the opening and closing alert and converts it to HTML with .Inner | markdownify.

HTML Generated:

The above shortcode will generate the following HTML.

<div class="alert alert-success" role="alert">...</div>
<div class="alert alert-info" role="alert">...</div>
<div class="alert alert-warning" role="alert">...</div>
<div class="alert alert-danger" role="alert">...</div>

Using Alert Shortcode:

To use the shortcode, in your post markdown file, add the following lines and replace the class value with success, info, warning or danger and then type your text that you want to highlight as the alert between the opening and closing alert.

{{< alert class="info" >}}
Your .Inner text is here
{{</ alert >}}

Now anytime you want to call out something you can use the alert shortcode to do it.

Create Single Line Shortcode

You can also create shortcodes that are single line shortcodes such as the one that this blog has for colour

layouts\colour.html:

{{ $colour := .Get 0 | safeCSS }}
{{ $colour2 := .Get 1 | safeHTML }}
<code style="background-color: {{ $colour }};"><span style="color: {{ $colour }}; filter:  grayscale(1) invert(1) contrast(100);">{{ $colour2 }}</span></code>

Using Colour ShortCode:

{{< colour "#e3fbc9" "colour" >}}

Wrap Up

Shortcodes can be a really powerful way to create reusable bits of HTML that extends what Hugo is able to directly generate from the markdown.

You can more in-depth about Custom Shortcodes in the Hugo docs.

In our next Hugo post, we are going to take a look at how to have all links that start with http or https open in a new tab without you having to do anything all at.