Create a Partial for Mermaid Initialization

Create a new file in your layouts/partials directory named mermaid-init.html. Add the following code to mermaid-init.html: HTML

1
2
3
4
<script type="module">
  import mermaid from '/js/mermaid.esm.min.mjs';
  mermaid.initialize({ startOnLoad: true });
</script>

Create a Shortcode for mermaid

Create a new file named mermaid.html in layouts/shortcodes/. Add the follwoing code to mermaid.html:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
{{- $scratch := .Page.Scratch -}}
{{- if not ($scratch.Get "mermaid-counter") -}}
  {{- $scratch.Set "mermaid-counter" 1 -}}
  {{- partial "mermaid-init.html" . -}}
{{- else -}}
  {{- $scratch.Add "mermaid-counter" 1 -}}
{{- end -}}
{{- $id := printf "mermaid-%d" ($scratch.Get "mermaid-counter") -}}
<div id="{{ $id }}">
    <pre class="mermaid">
{{- .Inner | safeHTML }}
    </pre>
</div>

Explanation of Changes:

  1. {{- if not ($scratch.Get “mermaid-counter”) -}}: Checks if mermaid-counter is not set (i.e., nil).
  2. {{- $scratch.Set “mermaid-counter” 1 -}}: If mermaid-counter is not set, it’s initialized to 1.
  3. {{- partial “mermaid-init.html” . -}}: The mermaid-init.html partial is loaded only when mermaid-counter is first set to 1.
  4. {{- else -}}: If mermaid-counter is already set, this else block is executed.
  5. {{- $scratch.Add “mermaid-counter” 1 -}}: In subsequent uses, mermaid-counter is incremented.

How It Works:

The very first time the mermaid shortcode is encountered on a page, mermaid-counter will be nil. The if condition will be true, and mermaid-counter will be set to 1. The mermaid-init.html partial will be loaded, ensuring the Mermaid library is loaded. On all subsequent uses of the mermaid shortcode on the same page, the else block will be executed, and mermaid-counter will be incremented. The mermaid-init.html partial will not be loaded again. This approach ensures that the Mermaid library is loaded only once per page, and only when a Mermaid diagram is present, without requiring changes to your base layout.

How to Use in Your Markdown

In your Hugo markdown files, you can use the mermaid shortcode like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21

### Mermaid Example one

\{\{< mermaid >}} # remove the escape character '\'
graph LR
    A[Start] --> B{Is it?};
    B -- Yes --> C[OK];
    B -- No ----> D[KO];
    C --> E[End];
    D --> E;
\\{\{< mermaid >}} # remove the escape character '\'

### Mermaid Example two
\{\{< mermaid >}} # remove the escape character '\'
flowchart TD
    A[Start] --> B{Is it?};
    B -- Yes --> C[OK];
    B -- No ----> D[KO];
    C --> E[End];
    D --> E;
\\{\{< mermaid >}} # remove the escape character '\'

demos

Example One

graph LR
    A[Start] --> B{Is it?};
    B -- Yes --> C[OK];
    B -- No ----> D[KO];
    C --> E[End];
    D --> E;

    

Example Two

flowchart TD
    A[Start] --> B{Is it?};
    B -- Yes --> C[OK];
    B -- No ----> D[KO];
    C --> E[End];
    D --> E;