django-pygments is a Django app that provides a template tag and 2 filters for doing syntax highlighting with Pygments. You can see it in use all over this site, particularly in the blogs but let's have a look at the end result anyway:
- class ListHtmlFormatter(HtmlFormatter):
- def wrap(self, source, outfile):
- return self._wrap_div(self._wrap_pre(self._wrap_list(source)))
- def _wrap_list(self, source):
- yield 0, '<ol>'
- for i, t in source:
- if i == 1:
- # it's a line of formatted code
- t = '<li><div class="line">%s</div></li>' % t
- yield i, t
- yield 0, '</ol>'
The integration is done using template filters and a template tag to add the markup to a <pre> block with the "lang" attribute set to the desired language. There's a demo page included in the distribution that covers most use cases.
- <h3>the "pygmentify" filter</h3>
- {{ snippet|pygmentify }}
- <br />
- <h3>the "pygmentify_inline" filter</h3>
- {{ snippet|pygmentify_inline }}
- <br />
- <h3>the "pygment" tag</h3>
- {% pygment %}
- <pre lang="bash">
- stefan$ ./manage.py runserver_cp
- Validating models...
- 0 errors found
- starting server with options {'ssl_certificate': None, 'workdir': None, 'verbose': 1, 'server_name': 'localhost', 'host': 'localhost', 'daemonize': 0, 'threads': 10, 'pidfile': None, 'shutdown_timeout': 60, 'ssl_private_key': None, 'server_group': 'www-data', 'port': 8000, 'server_user': 'www-data', 'request_queue_size': 5}
- Django version 1.2.1 SVN-13353, using settings 'proj.settings'
- Development server is running at http://localhost:8000/
- Quit the server with <CTRL>+C.
- [01/Aug/2010 17:34:39] "GET /labs/ HTTP/1.1" 200
- </pre>
- {% endpygment %}
This should pretty much cover all your highlighting needs (including RSS feeds with pygmentify_inline).



Leave a Comment :