I've had a few requests for information on how I syntax highlight my python code on this blog. Truth be told, I was using vim to output HTML and just pasting that into my blog posts. Pretty nasty.
So, I set about creating a template tag to do just that. It uses Pygments and BeautifulSoup, and has a few advantages over some similar code I found with the google world brain, namely:
- Will syntax highlight any code, not just python, and will do so automatically
- Only replaces <code> blocks
- Replaces all code blocks, so you can have a chunk of html and css in the same blog post for instance
- On failure just returns the original string
Anyway, here is the code:
from django import template
from pygments import highlight
from pygments.lexers import guess_lexer, PythonLexer
from pygments.formatters import HtmlFormatter
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.filter
def pygmentize(value):
try:
soup = BeautifulSoup(value)
code_blocks = soup.findAll('code')
for code in code_blocks:
try:
lexer = guess_lexer(code.string)
except ValueError:
lexer = PythonLexer()
code.replaceWith(highlight(code.string, lexer, HtmlFormatter()))
return str(soup)
except:
return value