/djang0byte/parser/templatetags/hightlight.py
Python | 39 lines | 19 code | 5 blank | 15 comment | 2 complexity | c654d6367d8fb26a86d63b5c77cdfa49 MD5 | raw file
Possible License(s): GPL-2.0
1# -*- coding: utf-8 -*- 2# This program is free software; you can redistribute it and/or modify 3# it under the terms of the GNU General Public License as published by 4# the Free Software Foundation; either version 2 of the License, or 5# (at your option) any later version. 6# 7# This program is distributed in the hope that it will be useful, 8# but WITHOUT ANY WARRANTY; without even the implied warranty of 9# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10# GNU General Public License for more details. 11# 12# You should have received a copy of the GNU General Public License 13# along with this program; if not, write to the Free Software 14# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 15# MA 02110-1301, USA. 16 17 18 19from pygments import highlight 20from pygments.lexers import get_lexer_by_name, PhpLexer 21from pygments.formatters import HtmlFormatter 22from pygments.util import ClassNotFound 23from BeautifulSoup import BeautifulSoup 24from django import template 25 26register = template.Library() 27 28@register.filter 29def highlight_template(value): 30 soup = BeautifulSoup(value) 31 for code in soup.findAll('code'): 32 lang = code['lang'] 33 try: 34 lexer = get_lexer_by_name(lang, encoding='utf-8', stripall=True, startinline=True) 35 except ClassNotFound: 36 lexer = get_lexer_by_name('text') 37 formatter = HtmlFormatter(encoding='utf-8', style='colorful', linenos='table', cssclass='highlight', lineanchors="line") 38 code.replaceWith(highlight(code.contents[0], lexer, formatter)) 39 return soup.renderContents().decode('utf8')