Loading...

Creating Custom Hugo Shortcodes

July 15, 2023
Web Development

Today I learned how to create custom shortcodes in Hugo. Shortcodes are a simple snippet inside your content files that Hugo will render using a predefined template.

Basic Shortcode

To create a basic shortcode, create a file in layouts/shortcodes/ directory. For example, to create a note shortcode:

<!-- layouts/shortcodes/note.html -->
<div class="note">
  {{ .Inner }}
</div>

Then use it in your markdown like this:

{{% note %}}
This is a note!
{{% /note %}}

Shortcodes with Parameters

You can also create shortcodes that accept parameters:

<!-- layouts/shortcodes/box.html -->
<div class="box {{ .Get "class" }}">
  {{ .Inner }}
</div>

And use it like:

{{% box class="info" %}}
This is an info box!
{{% /box %}}

Self-closing Shortcodes

Not all shortcodes need inner content. For example, a YouTube embed:

<!-- layouts/shortcodes/youtube.html -->
<div class="youtube">
  <iframe src="https://www.youtube.com/embed/{{ .Get 0 }}" allowfullscreen></iframe>
</div>

Use it like:

{{< youtube dQw4w9WgXcQ >}}

This has been super helpful for creating consistent UI elements across my site!