Use markdown-d2 without zensical¶
This guide shows how to draw diagrams in pages you build with Python-Markdown yourself, in a script or another site generator.
Add the fence¶
Hand pymdownx.superfences a custom
fence named d2, with
markdown_d2.formatter() as its format and markdown_d2.validator as its
validator:
md = markdown.Markdown(
extensions=["pymdownx.superfences"],
extension_configs={
"pymdownx.superfences": {
"custom_fences": [
{
"name": "d2",
"class": "d2",
"format": markdown_d2.formatter(root="pages"),
"validator": markdown_d2.validator,
}
]
}
},
)
html = md.convert("```d2\nyou -> page: write\n```")
root is the folder your imports and icons live in. The formatter takes the
same settings as in zensical.toml, as keyword
arguments.
Put the result in a page¶
Each figure carries its own CSS and script, so the HTML works wherever you put it. Place it in the body of your page template:
page = f"""<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>My page</title></head>
<body>{html}</body>
</html>
"""
Without a site theme, the page has no dark mode, so the light picture shows.
If your template marks dark mode, set dark_selector to match it, as
Change how a diagram looks
shows.
The whole script
"""Turn a Markdown page with a d2 block into HTML with Python-Markdown alone."""
from __future__ import annotations
from pathlib import Path
import markdown
import markdown_d2
md = markdown.Markdown(
extensions=["pymdownx.superfences"],
extension_configs={
"pymdownx.superfences": {
"custom_fences": [
{
"name": "d2",
"class": "d2",
"format": markdown_d2.formatter(root="pages"),
"validator": markdown_d2.validator,
}
]
}
},
)
html = md.convert("```d2\nyou -> page: write\n```")
page = f"""<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>My page</title></head>
<body>{html}</body>
</html>
"""
if __name__ == "__main__":
Path("page.html").write_text(page, encoding="utf-8")