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
Comments
maybe pass a lang parameter is better. And I don't know how to deal with CSS?
#
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
#
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'.
#
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
#