Login

Code syntax highlighting templatetag

Author:
badrunner
Posted:
September 15, 2007
Language:
Python
Version:
.96
Tags:
pygments syntax-highlightin beautifulsoup templatetag highlighting templatetags syntax
Score:
6 (after 6 ratings)

Replaces <code> blocks with syntax highlighted code. Use CSS to actually get the colours you want, look at pygments documentation for extracting css for various styles.

This snippet has the advantage of falling back on <pre> if anything goes wrong, and attempting to guess the syntax of code, falling back on python.

 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 6 years, 6 months ago
  2. Pygments Rendering Template Filter by ericflo 8 years, 3 months ago
  3. Parsing and Highlighting &lt;code&gt; Blocks by joshua 8 years, 3 months ago
  4. Markdown and Syntax Highlighting in Django by blinks 8 years, 2 months ago
  5. typygmentdown by ubernostrum 7 years, 9 months ago

Comments

Please login first before commenting.