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
Create a Shortcode for mermaid
Create a new file named mermaid.html in layouts/shortcodes/
.
Add the follwoing code to mermaid.html:
|
|
Explanation of Changes:
- {{- if not ($scratch.Get “mermaid-counter”) -}}: Checks if mermaid-counter is not set (i.e., nil).
- {{- $scratch.Set “mermaid-counter” 1 -}}: If mermaid-counter is not set, it’s initialized to 1.
- {{- partial “mermaid-init.html” . -}}: The mermaid-init.html partial is loaded only when mermaid-counter is first set to 1.
- {{- else -}}: If mermaid-counter is already set, this else block is executed.
- {{- $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:
|
|
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;