Pygmentify a code using template filter

The above snippet can be added as a custom filter for rendering code snippets in django templates. A simple '|render' next to any source code will do. To add css, use the following command to generate css file.

pygmentize -S emacs -f html > pygments-colorful.css

And link this css file to the template.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

fromdjangoimporttemplateregister=template.Library()frompygmentsimporthighlightfrompygments.formattersimportHtmlFormatterfrompygments.lexersimportget_lexer_by_name,guess_lexer@register.filterdefrender(content):"""Render this content for display."""formatter=HtmlFormatter(cssclass=u'source')try:# Guess a lexer by the contents of the block. lexer=guess_lexer(content)exceptValueError,e:# Just make it plain text. lexer=get_lexer_by_name(u'text',stripnl=True,encoding=u'UTF-8')result=highlight(content,lexer,formatter)returnunicode(result)