✨ How to Write a Hugo Shortcode

Hugo Shortcodes are reusable snippets to insert dynamic or complex content.

Introduction

Shortcodes make it easy to reuse the same logic or markup across your content. They help keep Markdown files readable while allowing you to insert dynamic or configurable elements when needed.

You should consider writing a shortcode when:

  • You need to reuse the same component in multiple places
  • You want to centralize or share data across different content files
  • You need to encapsulate complex or verbose HTML
  • You want to ensure consistent presentation across posts
  • You need to embed third-party content (videos, tweets, code snippets, etc.)
  • You want to separate content from layout and styling concerns
  • You need conditional rendering based on parameters or context
  • You want to provide simple, author-friendly building blocks instead of raw HTML

The Basics

To call a shortcode in your post, use its filename (without .html).

  • Use {{% %}} when the shortcode output contains Markdown that must be rendered
  • Use {{< >}} when the shortcode outputs HTML only (preferred for performance)

Examples:

  • {{% parameters params.yaml %}} # Markdown-aware
  • {{< parameters "params.yaml" >}} # HTML-only
  • {{% hugo/parameters params.yaml %}} # will look for ./layouts/shortcodes/hugo/parameters.html

In this post, we already saw that we can use shortcodes provided by the theme’s modules, but let’s write some custom ones.

Some use cases

Split code from articles

On this blog, I often include large code blocks. Instead of embedding them directly in Markdown, it’s often cleaner to keep them next to the article—for example, in a code/ or codes/ folder—and include them using a dedicated shortcode.

This approach makes the article easier to read and allows code snippets to be reused or updated independently of the content. Separating code from content keeps articles readable while letting code evolve independently. You can achieve this with a code-snippet shortcode.

  • Shortcode location: ./layouts/shortcodes/code-snippet.html

  • Content structure example:

1content/
2└─ posts/
3   └─ my-article/
4      ├─ index.md
5      ├─ codes/
6      │  └─ example.conf
  • The code:
 1{{- $name := printf "{code/%s,codes/%s}" ($.Get 0) ($.Get 0) }}
 2{{- $res := .Page.Resources.GetMatch $name }}
 3
 4{{- with $res }}
 5  {{- /* 1. Explicit language argument */ -}}
 6  {{- $lang := $.Get 1 | default "" }}
 7
 8  {{- /* 2. Fallback to file extension */ -}}
 9  {{- if not $lang }}
10    {{- $lang = replaceRE "^.*\\." "" .Name | lower }}
11  {{- end }}
12
13  {{- /* 3. Final fallback */ -}}
14  {{- if not $lang }}
15    {{- $lang = "txt" }}
16  {{- end }}
17
18  {{- highlight .Content $lang "" }}
19{{- else }}
20  {{- warnf "code snippet not found: %s" $name }}
21{{- end }}
  • The usage:

The language is taken from the file extension.

1{{< code-snippet example.txt>}} 

Or you can declare the language.

1{{< code-snippet example.txt ini>}}
  • The result:
    1[Test]
    2Description="Some random text to demonstrate the `code-snippet` shortcode."

Generate a table from YAML

You can generate a table from a configuration file using a shortcode. This is especially useful when you need to apply custom styling or effects, or when the dataset is large.

Instead of maintaining a long Markdown table, you can store the data in an a-long-list-of-stuffs.yaml file, which is easier to read and update over time.

So let’s create a shortcode that:

  • ✔ Generates a valid table
  • ✔ Automatically generates headers
  • ✔ Makes URLs clickable
  • ✔ Renders Markdown / HTML when present
  • ✔ Supports YAML / JSON / TOML inputs
  • The code in ./layouts/shortcodes/table-snippet.html:
  1{{/* -----------------------------------------------------------
  2table-snippet (positional parameters only)
  3
  4Usage:
  5table-snippet FILE [COLUMNS] [SORT] [FILTER]
  6
  7Examples:
  8table-snippet blogs.yaml
  9table-snippet blogs.yaml "name,description,url"
 10table-snippet blogs.yaml "name,url" name
 11table-snippet blogs.yaml "name,url" name "active"
 12------------------------------------------------------------ */}}
 13
 14{{/* ---------- Arguments ---------- */}}
 15{{- $file := .Get 0 -}}
 16{{- $cols := slice -}}
 17{{- if ge (len .Params) 2 -}}
 18  {{- $cols = split (.Get 1) "," -}}
 19{{- end -}}
 20
 21{{- $sortKey := "" -}}
 22{{- if ge (len .Params) 3 -}}
 23  {{- $sortKey = .Get 2 -}}
 24{{- end -}}
 25
 26{{- $filterKey := "" -}}
 27{{- if ge (len .Params) 4 -}}
 28  {{- $filterKey = .Get 3 -}}
 29{{- end -}}
 30
 31{{/* ---------- Load data ---------- */}}
 32{{- $data := slice -}}
 33{{- $found := false -}}
 34
 35{{/* ---------- 1. Page bundle resources ---------- */}}
 36{{- $patterns := slice -}}
 37
 38{{- if strings.Contains $file "." -}}
 39  {{- $patterns = slice
 40      (printf "table/%s" $file)
 41      (printf "tables/%s" $file)
 42      $file
 43  -}}
 44{{- else -}}
 45  {{- $patterns = slice
 46      (printf "table/%s.*" $file)
 47      (printf "tables/%s.*" $file)
 48      (printf "%s.*" $file)
 49  -}}
 50{{- end -}}
 51
 52{{- range $patterns -}}
 53  {{- if not $found -}}
 54    {{- with $.Page.Resources.GetMatch . -}}
 55      {{- $data = . | transform.Unmarshal -}}
 56      {{- $found = true -}}
 57    {{- end -}}
 58  {{- end -}}
 59{{- end -}}
 60
 61{{/* 2. Fallback to data/ */}}
 62{{- if not $found -}}
 63  {{- $cursor := site.Data -}}
 64  {{- $ok := true -}}
 65
 66  {{- range $k := split $file "/" -}}
 67    {{- if and (reflect.IsMap $cursor) (isset $cursor $k) -}}
 68      {{- $cursor = index $cursor $k -}}
 69    {{- else -}}
 70      {{- $ok = false -}}
 71    {{- end -}}
 72  {{- end -}}
 73
 74  {{- if and $ok (reflect.IsSlice $cursor) -}}
 75    {{- $data = $cursor -}}
 76    {{- $found = true -}}
 77  {{- end -}}
 78{{- end -}}
 79
 80{{- if not $found -}}
 81  {{- errorf "table-snippet: data source '%s' not found or not a list" $file -}}
 82{{- end -}}
 83
 84{{/* ---------- Schema validation ---------- */}}
 85
 86{{- if eq (len $data) 0 -}}
 87  {{- errorf "table-snippet: empty dataset in %s" $file -}}
 88{{- end -}}
 89
 90{{- if not (reflect.IsMap (index $data 0)) -}}
 91  {{- errorf "table-snippet: each row must be a map in %s" $file -}}
 92{{- end -}}
 93
 94{{/* ---------- Columns ---------- */}}
 95{{- $columns := slice -}}
 96
 97{{- if gt (len $cols) 0 -}}
 98  {{- $columns = $cols -}}
 99{{- else -}}
100  {{- range $k, $_ := index $data 0 -}}
101    {{- $columns = $columns | append $k -}}
102  {{- end -}}
103{{- end -}}
104
105{{/* Validate columns */}}
106{{- range $columns }}
107  {{- if not (isset (index $data 0) .) }}
108    {{- errorf "table-snippet: column '%s' not found in data %s" . $file -}}
109  {{- end }}
110{{- end }}
111
112{{/* ---------- Filtering (truthy key) ---------- */}}
113{{- if $filterKey -}}
114  {{- $filtered := slice -}}
115  {{- range $data -}}
116    {{- if and (isset . $filterKey) (eq (index . $filterKey) true) -}}
117      {{- $filtered = $filtered | append . -}}
118    {{- end -}}
119  {{- end -}}
120  {{- $data = $filtered -}}
121{{- end -}}
122
123{{/* ---------- Sorting ---------- */}}
124{{- if ne $sortKey "" }}
125  {{- if not (isset (index $data 0) $sortKey) }}
126    {{- errorf "table-snippet: sort key '%s' not found in data" $sortKey -}}
127  {{- end }}
128  {{- $data = sort $data $sortKey -}}
129{{- end }}
130
131{{/* ---------- Render table ---------- */}}
132<table class="table table-bordered table-hover table-striped">
133  <thead>
134    <tr>
135      {{- range $columns }}
136        <th>{{ . }}</th>
137      {{- end }}
138    </tr>
139  </thead>
140  <tbody>
141    {{- range $row := $data }}
142      <tr>
143        {{- range $columns }}
144          <td>
145            {{- with index $row . }}
146              {{- $val := printf "%v" . -}}
147              {{- if or (strings.HasPrefix $val "http://") (strings.HasPrefix $val "https://") }}
148                <a href="{{ $val }}" target="_blank" rel="noopener noreferrer">Link</a>
149              {{- else }}
150                {{- $val | markdownify -}}
151              {{- end }}
152            {{- end }}
153          </td>
154        {{- end }}
155      </tr>
156    {{- end }}
157  </tbody>
158</table>
  • The usage: {{< table-snippet list "name,description" >}}

  • The result:

    namedescription
    Element 1A description of element 1.
    Element 2A description of element 2.

Note: Because I generated HTML output, the right syntax is {{< >}}, not {{% %}}, which is Markdown-aware.

I then improved the table-snippet shortcode so that it:

  • ✔ Uses positional parameters only
  • ✔ Looks in the page bundle’s table/ or tables/ directory first, then data/
  • ✔ Handles nested paths such as rss/my-super-list
  • ✔ Supports optional sorting arguments
  • ✔ Supports optional Boolean filtering arguments
  • The usage now: {{< table-snippet DATA_FILE COLUMNS SORT FILTER >}}

  • Usage example: {{< table-snippet rss/list "name,description,url" name active >}}

Note about Hugo:

  • A page bundle (local to article/table or article/tables) is scoped to the page
  • The global data directory (data/) is reusable across the site
  • Hugo’s configuration loading is format-agnostic: .yaml, .yml, .json, and .toml files all work

Some ideas for future shortcodes

Here are a few additional shortcode ideas that would fit well in an IT-focused blog:

  • Diff viewer — render configuration or code changes in a readable diff format

  • Badges — display states such as Active, Disabled, or Deprecated with custom styles

  • Timelines — visualize chronological steps, migrations, or project history

Summary

Hugo shortcodes act as “controllers”. They allow you to:

📄 Keep Markdown clean and readable

🔁 Make data reusable across multiple posts (loading it from the page or data/)

🧩 Separate content from presentation

🛠 Make large amounts of data easy to maintain

⚠️ Handle errors and fail loudly if a file is missing

Well-designed shortcodes turn repetitive documentation patterns into reusable, expressive building blocks.

By contrast, partials are used for reusable rendering logic:

  • Receive normalized data
  • Output HTML
  • Apply formatting rules
Tuesday, November 10, 2026 Friday, January 16, 2026