Pygments Rendering Template Filter

 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. Code syntax highlighting templatetag by badrunner 5 years, 8 months ago
  2. Parsing and Highlighting &lt;code&gt; Blocks by joshua 6 years, 2 months ago
  3. Pygments Syntax highlighting template tag by girasquid 4 years, 5 months ago
  4. typygmentdown by ubernostrum 5 years, 9 months ago
  5. Markdown and Syntax Highlighting in Django by blinks 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

#

joshua (on February 27, 2007):

This is alot like mine, and probably faster. I use the class attribute, though, instead of trying to guess the code. (From my experience, the guessing is pathetically inadequate) Also, it falls back on 'text'.

#

mitsuhiko (on March 23, 2007):

Just a small hint: If you have a pygments powered webpage or application we would really like to know about it :D

If it's okay for you send us a link to the application and we'll add it to the list of projects

#

(Forgotten your password?)