Useful Markdown extensions in Python

I wanted to render some markdown in Python but with the following extra features:

For URLizing the best solution I've found is r0wb0t/markdown-urlize - it's not available on PyPI so you have to download the file and import from it.

The other two features can be handled by the toc and fenced_code extensions, both of which are included with Python Markdown and can be activated by passing their names as strings to the extensions= list.

Here's what I ended up doing (in a Django view):

from mdx_urlize import UrlizeExtension
import markdown
import pathlib

def docs(request):
    content = (pathlib.Path(__file__).parent / "").read_text()
    md = markdown.Markdown(
        extensions=["toc", "fenced_code", UrlizeExtension()], output_format="html5"
    html = md.convert(content)
    return render(
            "content": html,
            "toc": md.toc,

And in the docs.html template:

{% extends "base.html" %}

{% block title %}Documentation{% endblock %}

{% block content %}
{{ toc|safe }}
{{ content|safe }}
{% endblock %}

Created 2021-04-03T21:22:12-07:00 · Edit