Django code highlight template filter
来源地址:http://snipperize.todayclose.com/snippet/py/Django-code-highlight-template-filter--24910/
- 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
转载于:https://blog.51cto.com/axiii/301206