Adding Mermaid.js to Zola

  /   2 minutes   /   tech   zola   mermaid   howto  

Contents

What is Mermaid? Why do I want it?

According to the mermaid-js repo:

Mermaid is a JavaScript-based diagramming and charting tool that uses Markdown-inspired text definitions and a renderer to create and modify complex diagrams. The main purpose of Mermaid is to help documentation catch up with development.

I don’t have a good reason to want it. I think it’s neat. That’s enough for me.

I use Zola for this blog’s static site generation. I thought it would be nice to make using Mermaid more convenient to use directly in my Markdown content. This isn’t really necessary for this simple example, but it demonstrates how Shortcodes work in Zola.

You can see it in action on my about page. I used it to create these goofy timelines of where I’ve worked and lived. It serves no real purpose. It’s just neat.

Head over to mermaid.live if you want to play around with it. It’s fun!

Add Mermaid to your Zola theme

First you need to install the Mermaid package. If you’re cool with a CDN, you just need this at the end of your <body>:

<body>
  ... all your body content here ...
  <script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
    mermaid.initialize({ startOnLoad: true });
  </script>
</body>

If you want to deploy it instead of using the CDN, follow the well documented installation instructions.

To add this to my blog’s Zola template, I added it into my templates/index.html. Your template may differ.

Create a Mermaid Shortcode

Shortcodes are an awesome way to make using things like this super convenient to use directly in your Markdown.

To add one for Mermaid, I created a file named templates/shortcodes/mermaid.html with this content:

<pre class="mermaid">
{{ body }}
</pre>

I mean, there’s really not much to this. 😀

Using the Shortcode

Now, when I want a diagram, I use the shortcode from my Markdown content like this:

{% mermaid() %}
graph TD
    A[Enter Chart Definition] --> B(Preview)
    B --> C{decide}
    C --> D[Keep]
    C --> E[Edit Definition]
    E --> B
    D --> F[Save Image and Code]
    F --> B
{% end %}

Which should end up looking like this:

graph TD
    A[Enter Chart Definition] --> B(Preview)
    B --> C{decide}
    C --> D[Keep]
    C --> E[Edit Definition]
    E --> B
    D --> F[Save Image and Code]
    F --> B

Going Further

As I said above, this is a super simple example. Shortcodes can do much more than this. Check out the documentation to learn more.