Login

Pygments Rendering Template Filter

Author:
ericflo
Posted:
February 26, 2007
Language:
Python
Version:
Pre .96
Score:
11 (after 11 ratings)

Finds all <code></code> blocks in a text block and replaces it with pygments-highlighted html semantics. It tries to guess the format of the input, and it falls back to Python highlighting if it can't decide. This is useful for highlighting code snippets on a blog, for instance.

 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
from django import template
import re
import pygments

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 = pygments.lexers.guess_lexer(code_string)
            except ValueError:
                lexer = pygments.lexers.PythonLexer()
            pygmented_string = pygments.highlight(code_string, lexer, pygments.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:]
        return to_return
    except:
        return value

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

limodou (on February 26, 2007):

maybe pass a lang parameter is better. And I don't know how to deal with CSS?

#

ericflo (on February 26, 2007):

Limodou: The reason why I made it this way is because I may have several different types of code snippets per text object, and I want it to try and automatically detect the language of those code snippets.

As for the CSS: You can create your own style if you like, but I have a context processor which passes in this dictionary: {'pygments_style' : HtmlFormatter().get_style_defs('.highlight')}

And you'll have to have a: from pygments.formatters import HtmlFormatter

#

Please login first before commenting.