July 18, 2020

Add mermaid support to hugo code fences

Mermaid js is a visualisation tool commonly used in many web applications. Below is a way to allow code block support for mermaid in hugo markdown files similar to how StackEdit has achieved this. There seems to exists themes in Hugo that supports mermaid such as Learn, but really any theme should be allowed to support this in a easy way. Lets go!

Add mermaid support to hugo

Below is two ways to do this. Both can be used at the same time, but to make shortcodes work step 1 needs to be implemented.

  1. To use code fences for markdowns add following lines to the bottom of themes/[your-theme]/layouts/partials/footer.html file
<!-- Add mermaid min js file -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/8.6.0/mermaid.min.js" crossorigin="anonymous"></script>
<!-- Initializes mermaid js.
     Main reason to use .init rather than .initialize is that .init allows to pass in a class selector.
     Hugo's markdown code fences ```mermaid ``` will create a html code block with class .language-mermaid.
     This can then be used by mermaid to generate the correct diagrams with code fences
-->
<script>
    mermaid.init(undefined, '.language-mermaid');
</script>

This will init the mermaid script to all your footer pages.

  1. To allow a shortcode to hugo markdown files create hugo shortcode for mermaid themes/[your-theme]/layouts/shortcodes/mermaid.html and add following code into it
{{ $_hugo_config := `{ "version": 1 }` }}

<div class="mermaid" align="{{ if .Get "align" }}{{ .Get "align" }}{{ else }}center{{ end }}">{{ safeHTML .Inner }}</div>

The above code is a sample from Learn theme and will allow a shortcode syntax for your markdown files.

Example code fences

I prefer this approach as it actually uses code fences that is a standard withing markdown syntax.

```mermaid
graph TD
A[Christmas]  -->|Get money| B(Go shopping)
B --> C{Let me think}
C -->|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]
```

will render as

graph TD
  A[Christmas]  -->|Get money| B(Go shopping)
  B --> C{Let me think}
  C -->|One| D[Laptop]
  C -->|Two| E[iPhone]
  C -->|Three| F[fa:fa-car Car]

Example shortcode

{{< mermaid  align="left"  theme="dark" >}} 
    graph TD
      A[Christmas]  -->|Get money| B(Go shopping)
      B --> C{Let me think}
      C -->|One| D[Laptop]
      C -->|Two| E[iPhone]
      C -->|Three| F[fa:fa-car Car]
{{< /mermaid >}}

will render as

graph TD A[Christmas] -->|Get money| B(Go shopping) B --> C{Let me think} C -->|One| D[Laptop] C -->|Two| E[iPhone] C -->|Three| F[fa:fa-car Car]

Whats next?

Start writing your pages and posts in hugo with mermaid code fences or shortcode. Also read the mermaid documentation for the different diagram syntax.

comments powered by Disqus

© Anis Alekic 2020