- from pygments import highlight
- from pygments.lexers import get_lexer_by_name, PhpLexer
- from pygments.formatters import HtmlFormatter
- from pygments.util import ClassNotFound
- @register.filter
- def highlight_code(code, lang):
- if code is not None:
- try:
- # startinline is for PhpLexer so that it doesn't
- # require a <?php
- lexer = get_lexer_by_name(lang, encoding='utf-8', stripall=True, startinline=True)
- except ClassNotFound:
- lexer = get_lexer_by_name('text')
- formatter = HtmlFormatter(encoding='utf-8', style='colorful', linenos='table', cssclass='highlight', lineanchors="line")
- return highlight(code, lexer, formatter)
- else:
- return code
本文转自阿汐 51CTO博客,原文链接:http://blog.51cto.com/axiii/301206,如需转载请自行联系原作者