Home » Labs »

django-pygments

django-pygments

Django - Pygments integration

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:

  1. class ListHtmlFormatter(HtmlFormatter):
  2. def wrap(self, source, outfile):
  3. return self._wrap_div(self._wrap_pre(self._wrap_list(source)))

  4. def _wrap_list(self, source):
  5. yield 0, '<ol>'
  6. for i, t in source:
  7. if i == 1:
  8. # it's a line of formatted code
  9. t = '<li><div class="line">%s</div></li>' % t
  10. yield i, t
  11. 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.

  1. <h3>the "pygmentify" filter</h3>
  2. {{ snippet|pygmentify }}
  3. <br />
  4. <h3>the "pygmentify_inline" filter</h3>
  5. {{ snippet|pygmentify_inline }}
  6. <br />
  7. <h3>the "pygment" tag</h3>
  8. {% pygment %}

  9. stefan$ ./manage.py runserver_cp
  10. Validating models...
  11. 0 errors found
  12. 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}

  13. Django version 1.2.1 SVN-13353, using settings 'proj.settings'
  14. Development server is running at http://localhost:8000/
  15. Quit the server with <CTRL>+C.
  16. [01/Aug/2010 17:34:39] "GET /labs/ HTTP/1.1" 200

  17. {% endpygment %}

This should pretty much cover all your highlighting needs (including RSS feeds with pygmentify_inline).



Leave a Comment :

(required)


(required)




(required)





 
Page generated in: 0.07s