In a recent article, I added a code block for MermaidJS and found that neither Hugo nor my theme (PaperMod) would support MermaidJS. It rendered the code block as-is in raw form without converting it into a pretty diagram.
I was able to add support for MermaidJS by making a very small change to how Hugo renders the page.
Create a new file called layouts/partials/extend_head.html if it doesn’t already exist and paste in the following code:
{{ if .Params.mermaid }}
<script type="module">
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
mermaid.initialize({ startOnLoad: true });
// Convert code blocks to mermaid divs
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('pre code.language-mermaid').forEach(function(block) {
const pre = block.parentElement;
const div = document.createElement('div');
div.className = 'mermaid';
div.textContent = block.textContent;
pre.replaceWith(div);
});
mermaid.run();
});
</script>
{{ end }}
And then in your post’s frontmatter where you want to display MermaidJS, you simply add:
mermaid: true
Refresh and see the MermaidJS diagram. Easy!