Add Mermaid.js support to Hugo

Info: You can override content of your templates when creating the file with the same path in the root-directory of your hugo page. For example, to override themes/hyde-hyde/layouts/404.html you need to create layouts/404.html. This way you don’t need to keep the complete Theme in your own version control and keep instead just modified files.

HowTo

  1. Define a default template for mermaid markup in layouts/_default/_markup/render-codeblock-mermaid.html with the following content
    <div class="mermaid">
      {{- .Inner | safeHTML }}
    </div>
    {{ .Page.Store.Set "hasMermaid" true }}
    
  2. Override a Content-Template (for example the following) by coping it from themes/<theme-name>/layouts/partials/page-single/content.html to layouts/partials/page-single/content.html and add the following at the end
    {{ if .Page.Store.Get "hasMermaid" }}
      <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
      <script>
        mermaid.initialize({ startOnLoad: true });
      </script>
    {{ end }}
    

Your layouts folder should look like this now (if you didn’t do additional overrides already): Template-Folder

Let’s try if it works

The Code-Block has to start with ```mermaid

Mermaid-Example

graph LR; A-->B;

Sources and further reading

Introduction to Mermaid.js
https://mermaid-js.github.io/mermaid/#/

Hugo Articles:
https://gohugo.io/content-management/diagrams/#mermaid-diagrams
https://gohugo.io/templates/views/