Use mermaid with code fences
Issue
The Hugo theme Learn supports mermaid diagrams out of the box by using a custom shortcode. However, it’s not possible to use code fences syntax like
```mermaid
// Graph definition
When using Gitlab, this poses a problem. Gitlab requires the backticks for defining code blocks, which means that mermaid diagrams will not be rendered in Gitlab when using the shortcode provided by the theme.
Solution
When using code fences syntax for mermaid code blocks, you’ll notice that Hugo turns this into <code class="language-mermaid">...</code>
. Turns out it’s possible to tell mermaid which classes to look for when searching for graph definitions.
Simply add this at the end of your body:
{{ $mermaid := resources.Get "/path/to/mermaid.min.js" }}
<script src="{{ $mermaid.RelPermalink }}"></script>
<script>
window.onload = function() {
mermaid.init(undefined, ".language-mermaid");
};
</script>
This configures mermaid to search for nodes with class “language-mermaid”. These will be rendered as diagrams. Gitlab will render the diagram correctly, too.
Granted, this solution is far from perfect (the <code>
tag is wrapped in two other tags defining settings which are specific to the highlighting theme in use), but it works well with both Hugo and Gitlab.