Syntax Highlighting in Django with Markdown and Pygments
I find Markdown to be a more readable and usable alternative to XHTML/CSS for formatting text, and I use it to format my articles at this Django-powered blog. When implementing syntax highlighting for code blocks within text, I searched for existing solutions and found many approaches that were too complicated and had shortcomings. After more research, I realized that syntax highlighting works out of the box in Django if you have a recent version of Markdown.
Here are the required steps to enable syntax highlighting in your Django application. First, install python-markdown version 2.0+ and python-pygments. Pygments is a syntax highlighter written in Python. Markdown 2.0+ has an extension system and comes with a syntax highlighting extension that uses Pygments. This extension is called CodeHilite. To use it, add the following to a Django template:
{% load markup %} {{ text|markdown:'codehilite' }}
Next, you need to create a stylesheet that defines colors for syntax highlighting. To do so, run the following command:
$ pygmentize -S default -f html -a .codehilite > code.css
Include code.css in your template.
Now, to create a syntax-highlighted code block, indent the block by 4 spaces and declare the language of the block at the first line, prefixed by ::: (3 colons). This is better explained by example. The following text:
:::python print 'Hello, World.'
Produces the following syntax-highlighted code block:
print 'Hello, World.'
Keep in mind that Markdown allows embedded HTML elements by default. You shouldn't enable this if the source of the text is untrusted. To disable HTML elements, use the following in your Django template instead:
{% load markup %} {{ text|markdown:'safe,codehilite' }}
Pygments supports a long list of languages and styles. Be sure to check the demos too.
- | Permalink
- | 1 comment
- | Posted by Ayman Hourieh on April 25, 2010.



