Pygments Syntax highlighting template tag

 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 4 years, 10 months ago
  2. Code syntax highlighting templatetag by badrunner 4 years, 4 months ago
  3. Pygments Rendering Template Filter by ericflo 4 years, 11 months ago
  4. pygments stylize by mgiger 4 years, 6 months ago
  5. Parsing and Highlighting <code> Blocks by joshua 4 years, 11 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.

#

(Forgotten your password?)