- 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
- Generate and render HTML Table by LLyaudet 1 day, 21 hours ago
- My firs Snippets by GutemaG 5 days, 6 hours ago
- FileField having auto upload_to path by junaidmgithub 1 month, 1 week ago
- LazyPrimaryKeyRelatedField by LLyaudet 1 month, 2 weeks ago
- CacheInDictManager by LLyaudet 1 month, 2 weeks ago
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
#
Please login first before commenting.