Skip to content

Commit 2ed8f35

Browse files
committed
Useful Markdown extensions in Python
1 parent 19b2979 commit 2ed8f35

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Useful Markdown extensions in Python
2+
3+
I wanted to render some markdown in Python but with the following extra features:
4+
5+
- URLize any bare URLs in the content, like GFM
6+
- Handle `` ```python `` at the start of a block without showing the `python` bit (even if no syntax highlight is applied)
7+
- Show a table of contents
8+
9+
For URLizing the best solution I've found is [r0wb0t/markdown-urlize](https://github.com/r0wb0t/markdown-urlize) - it's not available on PyPI so you have to download the [mdx_urlize.py](https://github.com/r0wb0t/markdown-urlize/blob/master/mdx_urlize.py) file and import from it.
10+
11+
The other two features can be handled by the [toc](https://python-markdown.github.io/extensions/toc/) and [fenced_code](https://python-markdown.github.io/extensions/fenced_code_blocks/) extensions, both of which are included with Python Markdown and can be activated by passing their names as strings to the `extensions=` list.
12+
13+
Here's what I ended up doing (in a Django view):
14+
15+
```python
16+
from mdx_urlize import UrlizeExtension
17+
import markdown
18+
import pathlib
19+
20+
def docs(request):
21+
content = (pathlib.Path(__file__).parent / "docs.md").read_text()
22+
md = markdown.Markdown(
23+
extensions=["toc", "fenced_code", UrlizeExtension()], output_format="html5"
24+
)
25+
html = md.convert(content)
26+
return render(
27+
request,
28+
"docs.html",
29+
{
30+
"content": html,
31+
"toc": md.toc,
32+
},
33+
)
34+
```
35+
And in the `docs.html` template:
36+
37+
```html+django
38+
{% extends "base.html" %}
39+
40+
{% block title %}Documentation{% endblock %}
41+
42+
{% block content %}
43+
<h1>Documentation</h1>
44+
{{ toc|safe }}
45+
{{ content|safe }}
46+
{% endblock %}
47+
```

0 commit comments

Comments
 (0)