Login

pygments stylize

Author:
mgiger
Posted:
August 1, 2007
Language:
Python
Version:
.96
Tags:
pygments templatetags
Score:
5 (after 5 ratings)

Simple tag to enable easy parsing of inline code within a template. Usage: {% stylize "language" %}...language text...{% endstylize %}. Make sure to set the language for Pygments to parse as the first argument to the tag. You will also need to include a copy of the CSS that Pygments uses. The Pygments library is required for this 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
from django.template import Library, Node, resolve_variable
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

register = Library()

# usage: {% stylize "language" %}...language text...{% endstylize %}
class StylizeNode(Node):
	def __init__(self, nodelist, *varlist):
		self.nodelist, self.vlist = (nodelist, varlist)

	def render(self, context):
		style = 'text'
		if len(self.vlist) > 0:
			style = resolve_variable(self.vlist[0], context)
		return highlight(self.nodelist.render(context),
				get_lexer_by_name(style, encoding='UTF-8'), HtmlFormatter())

def stylize(parser, token):
	nodelist = parser.parse(('endstylize',))
	parser.delete_first_token()
	return StylizeNode(nodelist, *token.contents.split()[1:])

stylize = register.tag(stylize)

More like this

Comments

semente (on August 1, 2007):
<p>Thanks!!!</p>

#

glerm (on March 19, 2008):
<p>hey,</p> <p>I could not understand how do I get static CSS from pygment modules.</p> <p>(as you said in: "You will also need to include a copy of the CSS that Pygments uses." )</p> <p>I know it's maybe a little bit out of scope of this tutorial to learn how to use pygment, but I hope it's simple, isn't it?</p> <p>Seems like you have to generate a CSS from pygmentyze with: </p> <p>$ pygmentize -S default -f html > style.css</p> <p>... and put it in the css django folder?</p> <p>It didn't worked to me.</p> <p>The text escaped but couldn't get the colors...</p> <p>What's missing?</p>

#

glerm (on March 20, 2008):
<p>ooops</p> <p>my fault.</p> <p>the path to my /media/css was wrong... Anyway Ileft the tip for the command line Css with pygmentize...</p> <p>I hope it helps others</p>

#

blis102 (on July 14, 2008):
<p>Would there be any way to use this through the Django Admin interface, say using highlighting code in a flatpage?</p> <p>Im pretty sure you cant use template code in anything but the templates themselves, but what would be a way to use the syntax highlighting anywhere within a flatpage body (or even in other models, like say, an article body)?</p> <p>Thanks!</p>

#

Please login first before commenting.