Generate Diagrams in Jekyll with Mermaid

On This Page

There are many plugins available that you can use, but it’s simpler to manipulate and render diagrams using JavaScript rather than relying on Plugins. This approach allows for more flexibility how diagrams are generated and displayed

Add Mermaid Js

To enable Mermaid diagrams, first add the following Mermaid script to your Jekyll site:

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

Create a Mermaid Diagram

Now, you can create a Mermaid diagram in your Markdown file. Here is an example of a simple flowchart:

<pre class="mermaid">
        graph TD
        A[Client] --> B[Load Balancer]
        B --> C[Server01]
        B --> D[Server02]
</pre>
        graph TD
        A[Client] --> B[Load Balancer]
        B --> C[Server01]
        B --> D[Server02]

Render Diagrams from Markdown Code Blocks

It easier if Mermaid diagrams in Markdown code blocks automatically rendered.

<script type="module">
  import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
  mermaid.initialize({ startOnLoad: true });
  document.querySelectorAll('pre > code.language-mermaid').forEach((codeBlock) => {
    codeBlock.parentElement.outerHTML = `<pre class="mermaid">${codeBlock.textContent}</pre>`;
  });
</script>

This script finds all code blocks with the language-mermaid class and converts them into pre blocks with the mermaid class, allowing Mermaid to render them dynamically.

See the Pen Untitled by Mrinal (@mrinalcs) on CodePen.

Drop Your Email

Add Your Note