Skip to content

Commit b493ace

Browse files
committed
Introduce startmermaid block tag
1 parent 6480710 commit b493ace

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

src/django_mermaid/templatetags/mermaid.py

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import ast
12
import json
23

34
from django import template
@@ -14,7 +15,9 @@
1415
@register.simple_tag
1516
@mark_safe
1617
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" %}
1821
1922
:param diagram: The mermaid diagram definition
2023
: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):
2831
html = "<div class=\"mermaid\">%s</div><script src=\"%s\"></script>" % (diagram or "", mermaid_uri)
2932
init_properties = {"startOnLoad": True, "theme": theme, "themeVariables": theme_variables}
3033
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

Comments
 (0)