Sunday, February 5, 2012

Python syntax highlighting in Django templates using Pygments

Highlighting code to be placed on your site is a pretty common need that has been addressed nicely by a number of open source projects. Pygments is great, but on it's own would take you a while to get set up. This guide is meant to get you set up with using pygments in your django templates in under 5 minutes.

Choose your syntax highlighting style

First, decide which pygments style you want to use by trying them out on the pygments site.

Install django-pygments

There's a nice project on github that gives you a couple template tags for using pygments.

Create a pygments css file

Using whichever  style you liked from the pygments site, you can use the pygmentize command in your terminal to generate a CSS file for marking up your code.

pygmentize -S vs -f html > vs.css

Mark up your django templates

You're now ready to make the changes to your templates. Just import your css file, load the template tags, wrap your pre-formatted code with the pygment template tag, and then label the code as whatever language you use.

<link href="/media/css/pygments/vs.css" media="screen" rel="stylesheet" type="text/css" />

{% load pygmentify %}
{% pygment %}
<pre lang="python">
import simplejson
import urllib2
{% endpygment %}