Skip to content
Ircama edited this page Nov 27, 2022 · 1 revision

mermaid extra

This extra feature allows mermaid support through the mermaid fenced code block, like in this example:

```mermaid
graph TD;
    A-->B;
    A-->C;
    B-->D;
    C-->D;
```

For activation, both 'fenced-code-blocks' and 'mermaid' extras are needed.

Configuration

  1. Add the 'fenced-code-blocks' and the 'mermaid' strings to the extras list:

    markdown2.markdown(md, extras=['fenced-code-blocks', 'mermaid'])
  2. Put the following <script> tag at the bottom of your <body>:

    <script type="module" defer>
      import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@9/dist/mermaid.esm.min.mjs';
      mermaid. Initialize({
        securityLevel: 'loose',
        startOnLoad: true
      });
      let observer = new MutationObserver(mutations => {
        for(let mutation of mutations) {
          mutation.target.style.visibility = "visible";
        }
      });
      document.querySelectorAll("pre.mermaid-pre div.mermaid").forEach(item => {
        observer.observe(item, { 
          attributes: true, 
          attributeFilter: ['data-processed'] });
      });
    </script>
  3. Optionally add mermaid-pre styling (related to the mermaid <PRE> tags):

    <style>
    .mermaid-pre {
        visibility: hidden;
    }
    </style>

    In this example, we set the default visibility of mermaid graphs to hidden, so that we can change it later with the javascript function in order to hide the initial rendering transition.

Full example

import markdown2

md = markdown2.markdown("""
```mermaid
graph TD;
    A-->B;
    A-->C;
    B-->D;
    C-->D;
```
""", extras=['fenced-code-blocks', 'mermaid'])

html_header = """<!DOCTYPE html>
<html>
  <head>
    <style>
    .mermaid-pre {
        visibility: hidden;
    }
    </style>
  </head>
  <body>
    <h1>Mermaid Example</h1>
"""

html_footer = """    <script type="module" defer>
      import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@9/dist/mermaid.esm.min.mjs';
      mermaid.initialize({
        securityLevel: 'loose',
        startOnLoad: true
      });
      let observer = new MutationObserver(mutations => {
        for(let mutation of mutations) {
          mutation.target.style.visibility = "visible";
        }
      });
      document.querySelectorAll("pre.mermaid-pre div.mermaid").forEach(item => {
        observer.observe(item, { 
          attributes: true, 
          attributeFilter: ['data-processed'] });
      });
    </script>
  </body>
</html>
"""

html = html_header + md + html_footer

fp = "test-markdown.html"
with open(fp, "w+", newline="", encoding="UTF-8") as f:
    f.write(html)

Open the file "test-markdown.html" with a browser.

Clone this wiki locally