pygments stylize

 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

  1. Pygments Syntax highlighting template tag by girasquid 5 years, 4 months ago
  2. Parsing and Highlighting <code> Blocks by joshua 7 years, 1 month ago
  3. Markdown and Syntax Highlighting in Django by blinks 7 years, 1 month ago
  4. typygmentdown by ubernostrum 6 years, 8 months ago
  5. Parsed RSS into template var by bram 5 years, 9 months ago

Comments

semente (on August 1, 2007):

Thanks!!!

#

glerm (on March 19, 2008):

hey,

I could not understand how do I get static CSS from pygment modules.

(as you said in: "You will also need to include a copy of the CSS that Pygments uses." )

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?

Seems like you have to generate a CSS from pygmentyze with:

$ pygmentize -S default -f html > style.css

... and put it in the css django folder?

It didn't worked to me.

The text escaped but couldn't get the colors...

What's missing?

#

glerm (on March 20, 2008):

ooops

my fault.

the path to my /media/css was wrong... Anyway Ileft the tip for the command line Css with pygmentize...

I hope it helps others

#

blis102 (on July 14, 2008):

Would there be any way to use this through the Django Admin interface, say using highlighting code in a flatpage?

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)?

Thanks!

#

(Forgotten your password?)