Login

Pygmentation

Author:
alcides
Posted:
June 24, 2008
Language:
Python
Version:
.96
Tags:
filter tag templatetag pygments code colorize color
Score:
1 (after 1 ratings)

Usage: (if you save it as pigmentation.py as I did)

{% load pigmentation %} {% autoescape off %} {{ somevariable|pygmentize }} {% endautoescape %}

There already a few of this code around, but this one is pretty clean, and includes css. It also works in both the development server and Dreamhost (python2.4 in my django config) without any unicode problems.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from django import template
import re
import pygments
import pygments.lexers as lexers
import pygments.formatters as formatters

register = template.Library()

regex = re.compile(r'<code>(.*?)</code>', re.DOTALL)

@register.filter(name='pygmentize')
def pygmentize(value):
    try:
        last_end = 0
        to_return = ''
        found = 0
        for match_obj in regex.finditer(value):
            code_string = match_obj.group(1)
            try:
                lexer = lexers.guess_lexer(code_string)
            except ValueError:
                lexer = lexers.PythonLexer()
            pygmented_string = pygments.highlight(code_string, lexer, formatters.HtmlFormatter())
            to_return = to_return + value[last_end:match_obj.start(1)] + pygmented_string
            last_end = match_obj.end(1)
            found = found + 1
        to_return = to_return + value[last_end:]
        to_return += u"<style>%s</style>" % formatters.HtmlFormatter().get_style_defs('.highlight')
        return to_return
    except:
        return value

More like this

  1. Syntax highlighting for tracebacks in console output by jezdez 2 years, 10 months ago
  2. HTML color code field by b23 6 years, 11 months ago
  3. pygments stylize by mgiger 7 years, 11 months ago
  4. Django template tag to hash/map a value to a unique web color. by danielsokolowski 3 years, 7 months ago
  5. Pygments Rendering Template Filter by ericflo 8 years, 4 months ago

Comments

hobbes006 (on June 26, 2008):

Hi,

I am getting some strange HTML characters like [HTML_REMOVED] [HTML_REMOVED] [HTML_REMOVED] [HTML_REMOVED] etc showing up in between my pre tags.

Any idea why that could be?

#

alcides (on July 27, 2008):

No idea, maybe you're using an old version of django that doesn't autoescape?

#

Please login first before commenting.