I spent a bit of time this evening putting together a template filter for Django that allows really trivial syntax coloring from within the templates themselves. You can access any of the Pygments lexers, or can attempt to have Pygments detect the appropriate lexer on its own. Here is a quick example:
{% load syntax_color %}
<p> Specifying the lexer for the snippet. </p>
{{ my_code_snippet|colorize:"ruby" }}
<p> Letting Pygments guess the lexer. </p>
{{ my_code_snippet|colorize }}
<p> Adding line numbers as well. </p>
{{ my_code_snippet|colorize_table }}
</p> <code>colorize_table</code> can take an argument as well.</p>
{{ my_code_snippet|colorize_table:"html+django" }}
This may not be tremendously helpful, but I think it's a nice example of how a simple template filter can do something fairly impressive. Read on for the installation details, or you can download the syntax_colorize app here.
Installation and Usage
Install the Pygments library. The easiest way is via
easy_install.sudo easy_install pygments
Download the
syntax_colorizeapp. You can grab it here.Place the
syntax_colorizeapp in your Python path. For OS X 10.5 it'll be something like this:ln -s /Users/will/libraries/syntax_colorize /Library/Python/python2.5/site-packages/syntax_colorize
Add it to your
INSTALLED_APPSsetting.INSTALLED_APPS = ( 'django.contrib.sites', 'syntax_colorize', 'etc etc', )
Create the CSS files for Pygments. I created a simple helper function in the
syntax_colorize/templatetags/syntax_color.pyfile, so simply navigate to the directory and fire up Python:cd syntax_colorize/templatetags/syntax_color.py pythonAnd then run these commands at the interpreter:
>>> import syntax_color >>> syntax_color.generate_pygments_css()
Then copy the created
pygments.cssfile into your media directory.Update your base template's head tag so that it includes the
pygments.cssfile. That will look something like:<head> <link rel="stylesheet" href="/media/pygments.css" type="text/css"> </head>
Create a simple view that will pass a template a snippet of code. The simple example I've used for testing looked like this:
from django.shortcuts import render_to_response def index(request): code = """def index(request): from django.shortcuts import render_to_response code = "(define x 10)" return render_to_response('index.html',{'code':code}) """ return render_to_response('index.html',{'code':code})
In a real use case you might be pulling the code from a database, or perhaps BigTable if you're using the GoogleAppEngine.
Now fire up the Django template where you're interested in using the syntax coloring. Remember that the context contains the variable
codewhich is a string containing some Python code. Coloring the contents ofcodewith the Python lexer will look like this:{% load syntax_color %} <p> Take a look at this code: </p> {{ code|colorize:"python" }} <p> Oh. Maybe you wanted it in a table? </p> {{ code|colorize_table:"python" }}
Using the
colorize_tablefilter creates the syntax colored snippet inside of a table with line numbering, but is otherwise the same as thecolorizefilter.
I hope that this snippet is useful, and let me know if you have any suggestions, comments or complaints.
Update 8/12 4:42 PM
I created a GitHub repository for this project. You can access it here. If you don't want to visit the GitHub page, you can use git to clone a local copy:
git clone git://github.com/lethain/django-syntax-colorize.git
mv django-syntax-colorize syntax_colorize
Renaming the directory isn't strictly necessary, but otherwise the above instructions won't work verbatim.
Wow, amazing. I didn't know that we could colorize with pygments using a templatetag. I import the markdown library in my django view and then apply markdown along with its plugin "codehilite". After a while I leant a better way and created a body_html field.
@@python def save(self): body_html = markdown.markdown(body, ['codehilite']) super(Entry, self).save()
In this way I saved some computations. But having a template filter is much more rewarding.
Any chance this can get into an svn repository anytime soon?
I would love to have this for Pinax.
Would a github repository be sufficient? I'll try to put one up today.
I updated the article above, but it is now possible to grab a copy of the code from the repository on GitHub.
Hope that'll work out.
Think it's safe to say that we would love to have this in django-extensions. Would that be an option for you ?
Then it would also be in pinax as well :)
I'd be more than glad to have it be incorporated into django-extensions. I've created an issue on the google code tracker with a patch.
Very nice. FYI for you. In my test, the code highlighting is correct, but the code block area highlighting only fully covers the table version with class="highlighttable". The non-table version has highlight classes but does not entirely highlight the code area. Also I did not find the css class entry for highlighttable anywhere. It appears that the table is capturing the highlight color correctly but somehow the code text otherwise escapes the highlight box when not enclosed in a table. I'm using Firefox 3.01 on Ubuntu Hardy Fluxbox window manager.
Reply to this entry