Fragments of verbose memory

冗長な記憶の断片 - Web技術のメモをほぼ毎日更新(準備中)

Apr 23, 2023 - 日記

HugoのブログにでMermaidの図を埋め込む

このブログはHugo というブログフレームワークを使っていますが、ここにMermaid で図を簡単に埋め込む方法をご紹介します。これによって、プログラムのフローチャートやシーケンス図などを簡単に生成できるようになります。

Mermaid は、マークダウン形式でフローチャートやシーケンス図、ガントチャートなどの図表を作成できる JavaScript のライブラリです。プログラムのフローやデータの流れを視覚化するのに役立ちます。

例えば以下のようなテキストを markdown に埋め込むことで

mindmap
  root((mindmap))
    Origins
      Long history
      ::icon(fa fa-book)
      Popularisation
        British popular psychology author Tony Buzan
    Research
      On effectiveness<br/>and features
      On Automatic creation
        Uses
            Creative techniques
            Strategic planning
            Argument mapping
    Tools
      Pen and paper
      Mermaid

このような図が生成されます

mindmapOriginsLong history
PopularisationBritish popular psychologyauthor Tony BuzanResearchOn effectivenessand featuresOn Automatic creationUsesCreative techniquesStrategic planningArgument mappingToolsPen and paperMermaid

やり方は簡単で Hugo のブログヘッダに以下のスクリプトを埋め込みます。

<script type="module">
  const querySelector = 'pre>code.language-mermaid[data-lang="mermaid"]';
  import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs";
  document.addEventListener("DOMContentLoaded", () => {
    // make the background white
    const mermaidElements = document.querySelectorAll(querySelector);
    for (let i = 0; i < mermaidElements.length; i++) {
      mermaidElements[i].style.backgroundColor = "#fff";
    }
    // Marmaid rendering
    mermaid.initialize();
    mermaid.run({ querySelector: querySelector });
  });
</script>

querySelectorをちょいちょい変えれば他のブログシステムなどにも簡単に対応できると思います。