天天看点

利用pygments实现django模板内的语法高亮

  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. @register.filter 
  6. def highlight_code(code, lang): 
  7.   if code is not None: 
  8.     try: 
  9.       # startinline is for PhpLexer so that it doesn't 
  10.       # require a <?php 
  11.       lexer = get_lexer_by_name(lang, encoding='utf-8', stripall=True, startinline=True) 
  12.     except ClassNotFound: 
  13.       lexer = get_lexer_by_name('text') 
  14.     formatter = HtmlFormatter(encoding='utf-8', style='colorful', linenos='table', cssclass='highlight', lineanchors="line") 
  15.     return highlight(code, lexer, formatter)   
  16.   else: 
  17.     return code 

 本文转自阿汐 51CTO博客,原文链接:http://blog.51cto.com/axiii/301206,如需转载请自行联系原作者