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>')

More like this

  1. Pygments Syntax highlighting template tag by girasquid 4 years, 5 months ago
  2. Pygments Rendering Template Filter by ericflo 6 years, 2 months ago
  3. Parsing and Highlighting &lt;code&gt; Blocks by joshua 6 years, 2 months ago
  4. Markdown and Syntax Highlighting in Django by blinks 6 years, 2 months ago
  5. Text Highlighting Filter by girasquid 4 years, 5 months ago

Comments

ubernostrum (on September 16, 2007):

See also the same thing as a template filter.

#

(Forgotten your password?)