/djang0byte/parser/templatetags/hightlight.py

https://code.google.com/p/djang0byte/ · Python · 39 lines · 19 code · 5 blank · 15 comment · 3 complexity · c654d6367d8fb26a86d63b5c77cdfa49 MD5 · raw file

  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. from pygments import highlight
  17. from pygments.lexers import get_lexer_by_name, PhpLexer
  18. from pygments.formatters import HtmlFormatter
  19. from pygments.util import ClassNotFound
  20. from BeautifulSoup import BeautifulSoup
  21. from django import template
  22. register = template.Library()
  23. @register.filter
  24. def highlight_template(value):
  25. soup = BeautifulSoup(value)
  26. for code in soup.findAll('code'):
  27. lang = code['lang']
  28. try:
  29. lexer = get_lexer_by_name(lang, encoding='utf-8', stripall=True, startinline=True)
  30. except ClassNotFound:
  31. lexer = get_lexer_by_name('text')
  32. formatter = HtmlFormatter(encoding='utf-8', style='colorful', linenos='table', cssclass='highlight', lineanchors="line")
  33. code.replaceWith(highlight(code.contents[0], lexer, formatter))
  34. return soup.renderContents().decode('utf8')