Code syntax highlighting templatetag

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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.replace('<code>', '<div class="highlight"><pre>').replace('</code>', '</pre></div>')

Comments

ubernostrum (on September 16, 2007):

See also the same thing as a template filter.

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.