Including Mermaid diagrams in Hugo

29.12.2022 Web Hugo Mermaid

As I migrated my blog to Hugo, I was looking for cool features I could spice up my blog with. I ran into mermaid.js, which allows users to generate complex graphs with Markdown syntax.

Basics

From a user’s perspective, Mermaid is quite simple. All you have to do is to write some Markdown:

1pie title Do you like Hugo?
2"Yes" : 90
3"Also yes, but in yellow" : 10

Based on these three lines of text, Mermaid generates this pie diagram:

pie title Do you like Hugo? "Yes" : 90 "Also yes, but in yellow" : 10

Hugo shortcode

Pretty cool, huh? So how can you include Mermaid on my Hugo website?

The easiest way to include custom code in your Markdown files are shortcodes. To create a new shortcode, we create a new file layouts/shortcodes/mermaid.html. This will create a new shortcode named mermaid.

 1<div class="mermaid">
 2    {{ .Inner | safeHTML }}
 3</div>
 4
 5{{ if le (.Page.Scratch.Get "mermaidInserted") 0 }}
 6
 7{{ .Page.Scratch.Add "mermaidInserted" 1 }}
 8
 9{{ $mermaid := resources.Get "js/mermaid.js" | minify | fingerprint }}
10<script type="application/javascript" src="{{ $mermaid.Permalink }}" defer></script>
11<script type="module">
12    mermaid.initialize({});
13</script>
14
15{{ end }}

Noticed the scratch mathematics? The two script blocks will only be placed on the current page if the shortcode has been used anywhere. It helps to include the necessary JavaScript file only when needed. Also, it is included only once.

You can get the latest version of mermaid.js here.

Usage

Now we can use the shortcode in our Markdown content files. You can see the result at the top of this blogpost.

1{{< mermaid >}}
2pie title Do you like Hugo?
3"Yes" : 90
4"Also yes, but in yellow" : 10
5{{< /mermaid >}}

Related posts

... some things you might also be interested in

How to block ChatGPT on your website
09.08.2023 | Web | nginx Apache ChatGPT AI