Markdown2 is a fast and complete Python implementation of Markdown, designed to closely match the behavior of the original Perl-implemented Markdown.pl. It offers a core Markdown parser and numerous extensions, known as 'extras,' for enhanced functionality like syntax highlighting, tables, and header IDs. The library is actively maintained with periodic releases and currently supports Python 3.9 and newer.
pip install markdown2Verified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates basic Markdown conversion using the `markdown()` function and how to enable 'extras' (extensions) for enhanced features like fenced code blocks. It also shows the class-based `Markdown` API for more persistent configuration.
Replace `extras=['code-color']` with `extras=['fenced-code-blocks']` in your `markdown2.markdown()` call or `Markdown` object initialization. Ensure Pygments is installed for syntax highlighting: `pip install Pygments`.
Always pass the HTML output from `markdown2.markdown()` through an HTML sanitization library like 'Bleach' before rendering it in a web browser, especially when dealing with untrusted input. Example: `import bleach; sanitized_html = bleach.clean(html_output)`.
Adhere strictly to Markdown syntax guidelines. Ensure blank lines separate block-level elements. Always put a space after `#` for headings. Maintain consistent indentation (usually 2 or 4 spaces) for lists and indented code blocks. Tools like Markdown linters can help catch these issues.
Install the library using pip: `pip install markdown2`
Ensure that the input Markdown text, especially any embedded HTML, is well-formed. Consider updating to the latest `markdown2` version, as some parsing issues may have been addressed.
Create an instance of the `Markdown` class first, then call the `convert` method on that instance, or use the module-level convenience function `markdown2.markdown()`: `import markdown2; markdowner = markdown2.Markdown(); html = markdowner.convert('*Hello*');` OR `html = markdown2.markdown('*Hello*')`Mark the `markdown2` output as 'safe' in your Django template to instruct Django not to escape the HTML: `{{ markdown_output|safe }}`If using `markdown2`, leverage its 'extras' system (e.g., `markdown2.markdown(text, extras=['extra_name'])`) or `link_patterns` functionality instead of attempting to manipulate `inlinepatterns`. If `inlinepatterns` functionality is essential, consider using the `markdown` library instead of `markdown2`.