Login

Pygments Syntax highlighting template tag

Author:
girasquid
Posted:
November 24, 2008
Language:
Python
Version:
1.0
Tags:
templatetag pygments highlighting syntax
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. Markdown and Syntax Highlighting in Django by blinks 8 years, 2 months ago
  2. Code syntax highlighting templatetag by badrunner 7 years, 8 months ago
  3. Pygments Rendering Template Filter by ericflo 8 years, 3 months ago
  4. pygments stylize by mgiger 7 years, 9 months ago
  5. Parsing and Highlighting <code> Blocks by joshua 8 years, 2 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.