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

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<!-- 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 -->
<script defer src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function () {
        // runs after defer
        mermaid.initialize({ startOnLoad: true });
    });
</script>

<div class="mermaid" align="{{ if .Get " align" }}{{ .Get "align" }}{{ else }}center{{ end }}">
    {{ safeHTML .Inner }}
</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
2
3
4
5
6
7
8
9
{{ if and (eq .Type "post") (.HasShortcode "mermaid") }}
<script defer src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function () {
        // runs after defer
        mermaid.initialize({ startOnLoad: true });
    });
</script>
{{ end }}

See HasShortcode | Hugo for details.

Share


See also