How to Load the JS a Hugo Shortcode Needs

The HasShortcode check is handy


Posted on Sun, May 26, 2024
Tags golang, hugo
golang, hugo
📝 This article is a translation of the original Japanese post. View original

Loading the JavaScript and CSS a Shortcode Needs in head

In Hugo, when you want to embed some customized functionality inside an article, Shortcodes | Hugo are handy.

On this blog too, I define my own shortcodes for cases like enabling mermaid.js or putting affiliate links inside articles.

1<!-- example of layouts/shortcodes/mermaid.html -->
2<div class="mermaid" align="{{ if .Get " align" }}{{ .Get "align" }}{{ else }}center{{ end }}">
3    {{ safeHTML .Inner }}
4</div>

Shortcodes are convenient, but you end up wanting to set up the JavaScript that a shortcode needs in head.

 1<!-- With this, using the shortcode multiple times would fetch the js multiple times, so I don't want to define it as part of the shortcode -->
 2<script defer src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
 3<script type="text/javascript">
 4    document.addEventListener('DOMContentLoaded', function () {
 5        // runs after defer
 6        mermaid.initialize({ startOnLoad: true });
 7    });
 8</script>
 9
10<div class="mermaid" align="{{ if .Get " align" }}{{ .Get "align" }}{{ else }}center{{ end }}">
11    {{ safeHTML .Inner }}
12</div>

Using HasShortcode Inside head

By writing the following inside head, you can load the JavaScript only when the page is a post and it uses the mermaid shortcode.

1{{ if and (eq .Type "post") (.HasShortcode "mermaid") }}
2<script defer src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
3<script type="text/javascript">
4    document.addEventListener('DOMContentLoaded', function () {
5        // runs after defer
6        mermaid.initialize({ startOnLoad: true });
7    });
8</script>
9{{ end }}

See HasShortcode | Hugo for details.

Share


See also