Adding Mermaid Diagrams to a Hugo Blog
As a diagramming library officially supported by GitHub, mermaid is undoubtedly worth a try, whether it serves as a supplementary illustration for the text or adds a touch of flexibility to the layout. Next, using the method shared by Sulv, I’ll introduce how to use mermaid for diagramming in Hugo through Shortcodes.
Steps
1. Add and edit mermaid.html
Add and edit layouts/shortcodes/mermaid.html in the site root directory.
| |
Add the following content:
| |
2. Modify extend_head.html
In the site root directory, use the following command to copy extend_head.html to the layouts/partials directory and edit it:
| |
Add the following content:
| |
3. Usage
Add the following field to the front matter of the article in which you want to use mermaid for diagramming:
| |
You can then use mermaid in the form of Shortcodes in the article body. At the same time, you can add the above setting to archetypes/defaults.md, so that the field is automatically added every time a new article is created. Also, changing true to false will disable mermaid diagramming.
An example of using this Shortcodes for diagramming is as follows:
| |
The result is as follows:
You can wrap this code with HTML to center it or apply other layouts:
| |
The result is as follows:
Here is the mermaid usage tutorial:
4. Supplementary Notes
The mermaid theme does not yet change in real time with the web page theme; after switching to dark mode, you need to refresh the page to see the effect.
In addition, previously mermaid.js was loaded asynchronously with async, but that can no longer be done now, because the file must be loaded before the mermaid theme is set. It is unclear whether this affects website performance; if you have a better suggestion, feel free to email me to make changes.
This is mermaid diagramming implemented with Shortcodes. Later I found another tutorial that does not require Shortcodes: Make the Hugo PaperMod theme support Mermaid, but it turned out to be invalid in my tests. If you are interested, you can also give it a try.