- A django template filter that highlights code with pygments.
Django code highlight template filter
1 from pygments import highlight
2 from pygments.lexers import get_lexer_by_name, PhpLexer
3 from pygments.formatters import HtmlFormatter
4 from pygments.util import ClassNotFound
5
6
7 @register.filter
8 def highlight_code(code, lang):
9 if code is not None:
10 try:
11 # startinline is for PhpLexer so that it doesn't
12 # require a <?php
13 lexer = get_lexer_by_name(lang, encoding='utf-8', stripall=True, startinline=True)
14 except ClassNotFound:
15 lexer = get_lexer_by_name('text')
16 formatter = HtmlFormatter(encoding='utf-8', style='colorful', linenos='table', cssclass='highlight', lineanchors="line")
17 return highlight(code, lexer, formatter)
18 else:
19 return code
Comments
-
mcbayrak 2010-01-24
i didnt tried but looks like very usuable thanks.
Sign in to leave a comment.

