Thursday, April 19, 2007

Using Mako in Django

It seems that Mako is one of the more powerful and faster template system for Python web development. In fact, Pylons is suppose to change in adapting Mako over Myghty soon. Since I'm using Django which uses its own template system, I was thinking I was out of luck. But fortunately, someone has written an adaptor for using Mako in Django!

I find it odd that there doesn't seem to be much talk about it. Maybe because it's only been out for a month or so. There isn't any documentation about it in his site, maybe he's just too busy. But I contacted him and he was quick in replying in how to getting it running. Thank you, Yi! So I want to help him out in return by writing a little guide on it so he doesn't have to answer annoying emails from newbies like me :)

1. Download his files and save them in a path where you can import them, like in python2.5\lib or just under python directory if you're using cygwin. If you're sure you're going to use just Mako or Genshi (which is an XML template system, so it's slower, but has many devoted followers), you can combine the and the one you're going to use into a single file to avoid filename conflicts of future libraries with filenmae (or you can rename to something else).

2. Follow instructions in installing Mako if it isn't installed already.

3. Add the following to your file of your Django project (here are my settings):

MAKO_TEMPLATE_DIRS = ('C:/Projects/mysite',)
# A tuple, specify the directories in which to find the mako templates,
# just like TEMPLATE_DIRS .
# default value is ('mako_templates',)

# A string, if specified, all of the compiled template module files will be
# stored in this directory.


you can put these anywhere in the file I believe, I put them under the TEMPLATE_DIRS definition to keep all template stuff together. The TEMPLATE_DIRS definition by the way, will not be used anymore as you're now using Mako's. But leaving it defined to some path will not hurt.

4. In your, add the following:

from mako_django import render_to_response

def some_function_named_in_urlpatterns(request):
return render_to_response('your_template.anything')

(I named it view_mktmpl.html, I believe the extension can be anything, but haven't really tried :).

5. Place your template file (your_template.anything), in where you specified in MAKO_TEMPLATE_DIRS. To learn more about writing a Mako template, see the Mako documentation.

hope this helps.