Login

Pygments Rendering Template Filter

Author:
ericflo
Posted:
February 26, 2007
Language:
Python
Version:
Pre .96
Tags:
template filter pygments highlighting code
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. Parsing and Highlighting &lt;code&gt; Blocks by joshua 8 years ago
  2. Code syntax highlighting templatetag by badrunner 7 years, 5 months ago
  3. Markdown and Syntax Highlighting in Django by blinks 7 years, 11 months ago
  4. typygmentdown by ubernostrum 7 years, 6 months ago
  5. Text Highlighting Filter by girasquid 6 years, 2 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.