Login

Pygments Syntax highlighting template tag

Author:
girasquid
Posted:
November 24, 2008
Language:
Python
Version:
1.0
Score:
-1 (after 1 ratings)

This template tag will attempt to apply pygments syntax highlighting to anything inside {% code %} and {% endcode %} tags. You can optionally pass in the language to highlight in the form of {% code 'lang' %} - if you don't, it will first try to guess the syntax, and then fall back to Python syntax highlighting.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from pygments import highlight
from pygments.lexers import *
from pygments.formatters import HtmlFormatter

@register.tag(name='code')
def do_code(parser,token):
    code = token.split_contents()[-1]
    nodelist = parser.parse(('endcode',))
    parser.delete_first_token()
    return CodeNode(code,nodelist)
    
class CodeNode(template.Node):
    def __init__(self,lang,code):
        self.lang = lang
        self.nodelist = code
        
    def render(self,context):
        try:        
            language = template.Variable(self.lang).resolve(context)
        except:
            language = self.lang
        code = self.nodelist.render(context)
        try:
            lexer = get_lexer_by_name(language)
        except:
            try:
                lexer = guess_lexer(code)
            except:
                lexer = PythonLexer()
        return highlight(code,lexer,HtmlFormatter(linenos='table'))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Tarken (on November 24, 2008):

I think we're missing a very important piece here: the imports

Other than that, cool!

#

girasquid (on November 26, 2008):

Whoops, sorry about that - I've added the pygments imports to the top of the snippet now.

#

Please login first before commenting.