I've been trying to add syntax highlighting to my django site. The problem is I'm getting the
and <br />
characters formatted as well. Is there a way to preserve these characterss? Here is the code I'm using:
from BeautifulSoup import BeautifulSoup
from django import template
from django.template.defaultfilters import stringfilter
import pygments
import pygments.formatters
import pygments.lexers
register = template.Library()
@register.filter
@stringfilter
def pygmentized(html):
soup = BeautifulSoup(html)
codeblocks = soup.findAll('code')
for block in codeblocks:
if block.has_key('class'):
try:
code = ''.join([unicode(item) for item in block.contents])
lexer = pygments.lexers.get_lexer_by_name(block['class'], stripall=True)
formatter = pygments.formatters.HtmlFormatter()
code_hl = pygments.highlight(code, lexer, formatter)
block.contents = [BeautifulSoup(code_hl)]
block.name = 'code'
except:
raise
return unicode(soup)
` or ` `. – Petri Lehtinen Mar 22 '11 at 06:32