Correct way to embed Mermaid.JS

I found 4 tutorials that all embed Mermaid differently:

This says: Add Diagrams to your Jekyll/Hugo/Gatsby blog with Mermaid JS · Code with Hugo

Add this code to layouts/shortcodes/mermaid.html:

<div class="mermaid">

and add this to unknown location:

{{ if (.Params.mermaid) }}
<!-- MermaidJS support -->
<script async src=""></script>
{{ end }}

This says: On The Other Hand · Integrating Mermaid JS Into Hugo

Add to layouts/shortcodes/mermaid.html:

{{ if ($.Page.Params.mermaid) }}
<script src="//"></script>
<script>!window.mermaid && document.write(unescape('%3Cscript src="/js/mermaid-8.9.1/mermaid.min.js"%3E%3C/script%3E'))</script>
{{ end }}
<div class="mermaid">

This says: skeptric - Diagrams in Hugo with Mermaid

Add to layouts/shortcodes/mermaid.html

{{ $_hugo_config := `{ "version": 1 }` }}
<div class="mermaid" align="{{ if .Get "align" }}{{ .Get "align" }}{{ else }}center{{ end }}">{{ safeHTML .Inner }}</div>

and in layouts/partials/site-header.html:

<script src=""></script>
<script>mermaid.initialize({ startOnLoad: true, securityLevel: 'loose'}});</script>

And this says: Build and display Mermaid.js diagrams in Hugo

Add to layouts/shortcodes/mermaid.html:

<script async type="application/javascript" src="">
  var config = {
    theme:'{{ if .Get "theme" }}{{ .Get "theme" }}{{ else }}dark{{ end }}',
    align:'{{ if .Get "align" }}{{ .Get "align" }}{{ else }}center{{ end }}'

<div class="mermaid">

What is the RIGHT way?

I doubt there is a right way, your mileage may vary.

Personally, I find the most elegant way to display mermaid diagrams is to make use of a code block render hook. This is how it is done in the docsy theme:

Please note that Mermaid is at version 10.0.2 now, which is ESM only. If you want to use the latest version of mermaid, you have to import mermaid as module.

1 Like

I agree with @deining.

This is simple:

GitHub uses the same approach—a fenced code block in markdown.

Would this make the script load all the time?

The 1 benefit of the short-code is that it only loads on certain pages that use it (or so it says).

The example in docs that I linked to:

{{ if .Page.Store.Get "hasMermaid" }}

If only loads JS for a page with a mermaid code block.

1 Like

@jmooring Where is .Page.Store documented? Nothing comes up in search, nothing listed on the page variables page. Is that supposed to be .Scratch?

Have a look here:

That’s true, this variable should be added, indeed.

1 Like

It seems the Algolia search takes some time to update. I looked up hasSuffix a few days ago after it was added in the last release and it was missing in the search. But now it is showing up.

Done with this commit.

1 Like