Warning! Ugly code ahead

For a django project - I needed a source code highlighter to display code segments in template. Considered markdown with codehilite extension since I have already came across it in HiSlain. It looked simple as described here. But it expects the code to be markdown formatted beforehand. I need to get source code from users and display it. So expecting that to be in markdown (or) formatting it is going be hectic. So decided to settle with the famous pygments library. After looking through some examples, cooked up this following code. This is implemented as a custom template filter for django. So any code can be pygmentified in templates by adding a '| render' filter. Below is that ugly code,


     from pygments import highlight
     from pygments.formatters import HtmlFormatter
     from pygments.lexers import get_lexer_by_name, guess_lexer
     @register.filter
     def render(content):
          """Render this content for display."""
          formatter = HtmlFormatter(cssclass=u'source')
          try:
        # Guess a lexer by the contents of the block.
            lexer = guess_lexer(content)
          except ValueError, e:
            # Just make it plain text.    
lexer = get_lexer_by_name(u'text', stripnl=True, encoding=u'UTF-8') result = highlight(content, lexer, formatter) return unicode(result)

The above is mostly self explanatory. The decorator above the method corresponds to registering that filter in django.

EDIT: I have added the above snippet and other useful snippets I cooked up here

happy hacking!

Published at : Tuesday May,10 2011 at 20:44 | Tags : hacking, django, | View Comments
Browse Archives
I am..
Azhagu Selvan SP
Atheist, FOSS enthusiast,
Pythonist, Student
Legal
Creative Commons License