44. 【GitHub Pages】🧩 How to Render Mermaid Diagrams on GitHub Pages (Jekyll)

topics: [“GitHubPages”, “Jekyll”, “Mermaid”, “JavaScript”, “Qiita”]


On Qiita, you can render flowcharts and state diagrams
simply by writing:

```mermaid

in Markdown.

However, on GitHub Pages (Jekyll),
the same syntax is rendered as a plain code block by default.

In this article, we explain how to:

Keep the same ` ```mermaid ` syntax as Qiita
and render Mermaid diagrams correctly on GitHub Pages

using a minimal, production-ready configuration.


🎯 Goal

We aim to achieve the following:


🧠 How It Works (Key Concept)

On GitHub Pages, the responsibilities are split as follows:

Therefore, we need to:

  1. Detect code.language-mermaid blocks
  2. Convert them into Mermaid-compatible DOM elements
  3. Let Mermaid.js render the diagrams

📦 Load Mermaid.js

First, load Mermaid.js in _includes/head.html.

<script defer src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>

📌 Notes


🛠 Convert Code Blocks for Mermaid

Next, replace Markdown-generated HTML
with Mermaid rendering targets.

<script>
  document.addEventListener("DOMContentLoaded", () => {
    if (!window.mermaid) return;

    // Convert code.language-mermaid → div.mermaid
    document.querySelectorAll("code.language-mermaid").forEach(code => {
      const pre = code.parentElement;
      const div = document.createElement("div");
      div.className = "mermaid";
      div.textContent = code.textContent;
      pre.replaceWith(div);
    });

    mermaid.initialize({ startOnLoad: false });
    mermaid.run();
  });
</script>

📌 Notes


✏️ Writing Mermaid in Markdown

This is exactly the same syntax as on Qiita.

flowchart TD
  A[Input V] --> B[Controller]
  B --> C[Plant]
  C --> D[Output I]

👉 This example represents a simple control block diagram
based on a V–I (voltage–current) flow.


🔍 Live Demo (Rendered Output)

You can confirm that Mermaid diagrams
are rendered correctly on this live page:

📌
Always verify that the diagram is rendered
as a diagram, not as a code block.


⚠️ Common Pitfalls


📝 Summary