1
+ import ast
1
2
import json
2
3
3
4
from django import template
14
15
@register .simple_tag
15
16
@mark_safe
16
17
def mermaid (diagram = None , theme = None ):
17
- """Render a mermaid diagram.
18
+ """Render a mermaid diagram, using a simple tag.
19
+
20
+ {% mermaid "graph LR; A-->B;" "dark" %}
18
21
19
22
:param diagram: The mermaid diagram definition
20
23
:param theme: The mermaid theme to use (default, forest, dark, neutral, base). See https://mermaid.js.org/config/theming.
@@ -28,3 +31,43 @@ def mermaid(diagram=None, theme=None):
28
31
html = "<div class=\" mermaid\" >%s</div><script src=\" %s\" ></script>" % (diagram or "" , mermaid_uri )
29
32
init_properties = {"startOnLoad" : True , "theme" : theme , "themeVariables" : theme_variables }
30
33
return html + "<script>mermaid.initialize(%s);</script>" % json .dumps (init_properties )
34
+
35
+
36
+ @register .tag (name = "startmermaid" )
37
+ def do_startmermaid (parser , token ):
38
+ """Render a mermaid diagram, using a block tag.
39
+
40
+ {% startmermaid "dark" %}
41
+ graph LR
42
+ A-->B
43
+ {% endmermaid %}
44
+
45
+ This tag is identical to the {% mermaid %} simple tag but allows usage as a block.
46
+ That can be useful for longer diagrams. Specifying the theme is optional.
47
+ """
48
+ # Split the token to try to capture a theme parameter if provided
49
+ bits = token .split_contents ()
50
+ if len (bits ) > 1 :
51
+ # Strip surrounding quotes
52
+ theme = ast .literal_eval (bits [1 ])
53
+ else :
54
+ theme = None
55
+
56
+ # Parse everything until the end tag 'endmermaid'
57
+ nodelist = parser .parse (('endmermaid' ,))
58
+ parser .delete_first_token ()
59
+
60
+ return MermaidNode (nodelist , theme )
61
+
62
+
63
+ class MermaidNode (template .Node ):
64
+ def __init__ (self , nodelist , theme ):
65
+ self .nodelist = nodelist
66
+ self .theme = theme
67
+
68
+ def render (self , context ):
69
+ # Render the diagram from the block
70
+ diagram_content = self .nodelist .render (context )
71
+ # Pass processing on to the simple template tag
72
+ return mermaid (diagram = diagram_content , theme = self .theme )
73
+
0 commit comments