Category Archives: Mako

Exploring Mako

I’d like to take a tour of Mako, Mike Bayer’s excellent Python template engine. First, a few comments on my column on adding event behaviours to Elixir:

1. The pastebin code has a few mistakes (I’m sure those interested will have spotted them); I noticed them of course just after I posted the code, but haven’t found any way to correct it (unlike in djangosnippets, for example, there does not seem any way to edit your pasted code).

Updated: here is the improved code.

2. Comments on the Elixir google group have been quite positive. As pointed out, the code could be definitely improved, it’s a bit repetitive for starters.

3. In the same vein, someone has provided an excellent example of adding validation DSLs to Elixir.

Now, on to Mako. Mako is loosely based on Myghty, which itself is based on Mason, a Perl template engine of some vintage that has been used for example by Amazon. Myghty was pretty cool, I had only used it in “hello world” stuff but it seemed a lot easier than for example Cheetah. Cheetah had a lot of hassles such as having to precompile master templates which made it a bit of a PITA at times (that might have been fixed by now; it’s been a while since I have used it).

Mako is a text-based template engine, unlike Kid or Genshi; you can therefore use it in producing non-SGML output such as email contents or JavaScript and CSS. It has a number of tags for doing stuff like inheritance, control flow syntax (same as Python, but with closing tags like endif for getting round the significant whitespace issue) and variable inclusion. The syntax and tags are very simple and a Python coder (or even web designer) should get up to speed with Mako very quickly.

The really nifty thing about Mako, however, is that it combines a lot of the best ideas from other template engines into one package. For example, inheritance is borrowed from Myghty, and also Django/Jinja.

Some template designers don’t like too much logic in their code – Django for example. In Django, using their standard template engine makes it hard to do anything more than if/else conditionals and for loops. This is by intention; templates are for designers only, and it enforces MVC – you have to move code into the controller (or Django “view”) or special tags.

The way I see it, there is no problem with logic in the view / template layer – as long as that code concerns itself only with presentation logic. Often however that logic can get convoluted and repetitive, and you want to cordon it off into a function. With Mako you can do this with namespaces. A namespace is essentially just a library of template code.

For example, say you have a Mako file, formutils.mako, which looks something like this:

<%def name="label(field, content)">
<label for="${field}">${content}</label>

Now in another file, you include the code in formutils.mako like so:

<%namespace name="form" file="/formutils.mako" />

Now you can call the functions defined in formutils.mako just like any other Python function:

${form.label('name', 'Your name:')}

For people who know Rails, this kind of like partials, but with simpler syntax. If you are using Pylons you can use helpers, but Mako namespaces are better if the code is more HTML than Python.

Another neat idea is template inheritance. In large web apps this is important because your site is often broken down into different modules or sections, each with 90% the same layout but maybe an extra stylesheet, menu, title etc. Some template engines don’t support inheritance or do it badly: Rails for example has layouts, but layouts cannot be (as far as I know) chained in any way, so you end up cutting and pasting code or putting in lots of conditionals; you can only replace the main body of the template, not selected pieces. They are also dependent on the controller layer, which kind of breaks MVC. In Mako you have a similar directive to namespaces:

<%inherit file='/base.mako' />

Now you can define functions in the same way in your base.mako file, for example:

<%def name='title()'>Hi de ho!</%def>

and call them in your template HTML code:


(note the use of self, which is important if you want inheritance to work).

Any template which inherits base.mako should output:

<title>Hi de ho!</title>

However, if you want to change the title you just need to override the title() function in your template:

<%def name='title()'>Ho de hi!</%def>

Then you get:

<title>Ho de hi!</title>

When you are building a large, complex web site this is really, really useful. I’m working on a large Rails project right now and this simple feature would be so handy.

One final word : Mako performance rocks, see the Mako home page for a comparative study. Mako out-performs even Cheetah and Django.


The Side Project

Side projects, if you have the time, are great way to keep your coding fresh. Most places I have worked in my IT career have been single-product businesses of varying size (tiny startups to medium sized companies). That is, you work on a single product or product family, using one language or platform, year after year. Now, depending the nature of your work and the nature of you, that can be interesting or deadly boring, or both; but often you just want to do something different, and the boss won’t let you. You may limp along all day in VB.NET, but at night fly in Perl; in office hours, you write accounting software macros; in your basement, Linux DVD drivers. At the water cooler, you are just a low-paid, invisible geek; on the OSS mailing lists, you are a guru, nay, a God.

So, the side project, be it open source or not, is one way to keep your coding skills fresh and your coding ego boosted (assuming, of course, you are good at what you do). And, who knows, it may one day bring you fame and fortune.

As an aside, I did work for a boss who was dead against developers doing side projects; he thought they should be 100% focused on our product, presumably saving their spare-time brain cycles for company use. To which I say: what an ass. Side projects not only are good for you, but they may be good for whomever you work for, as you get new ideas and perspectives that may be of use to the Man.

So, I have had an idea for some time about working on the perfect business web application. To be more exact, something which allows a company to manage its projects and sales, but without complexity and bloat. I’m thinking of an app that has blogs and wikis, so people and teams can build something as much from the ground up as well as from the management down. For example, you can keep up with your project as much with a blog as with Gantt charts and milestones, tag your meetings and contacts, add YouTube videos to your product lists.

These are all rather vague, Web 2.0-ish ideas, and at the moment half-baked and in need of some originality. And yes, I know 37Signals have Basecamp and Highrise, but they have yet to combine their individually decent products under a single roof and, to be honest, their focus on “simplicity” at all costs leaves their apps a nose short of greatness.

I don’t really plan on making money out of this; I’ll probably just post it on Google Code. I’m doing it because:

a) I do Ruby all day for bread and board, and I prefer to code in Python

b) I want to do stuff in Pylons, Elixir, Mako and other cool tools I’ve been writing about

c) I think there’s a kickass framework that can be built on these tools, but I want to harvest it from something that really works (more on this later)

d) I really think that businesses and organizations need something like this ( I may be completely wrong, of course)

e) You never know, it might make me rich and/or famous.

However, I have limited time: a full time job, and family commitments. Progress will be slow and sporadic. That’s OK , if I can at least get the ball rolling, and let others with more skill and time on their hands take over, then I’ll be happy, and I’ll go and start another side project, even if that side project is just mowing the lawn.

Pylons, or Python is fun again !

I’ve always liked Python. I started using it back in 2003, and it’s always been my first choice when writing stuff like sysadmin scripts, built tasks, RSS feed readers, that kind of thing.

However, my bread and butter is web development, and Python never had a compelling story for me in that field. Zope/Plone is horrendously bloated and complex (the infamous Z-shaped learning curve), Django is nice and well thought out, but I’ve found it more for developing dynamic web sites; it gets in the way too much for complex web apps. Turbogears started out well, but seems broken and lacking in direction these days. Then we have a number of smaller, or older, frameworks –, Quixote, snakelets, WebWare…either too small a developer base, not actively developed, or just not what I’m looking for.

So, for web development, I’ve used J(2)EE, PHP and more recently, Rails. The latter has been the most fun, and Ruby is a nice language to work with. However, despite the deluge of Ruby hype and praise (much of it justified) I still prefer Python. Maybe it just fits my brain better, maybe it’s the scope and size of the libraries. I find Ruby harder to understand and debug, perhaps because of its Perlish syntax and metaprogramming tricks. This is not meant as flamebait: I just find Python easier for getting things done.

I can think better in Python; I find the process harder in Ruby, and often find there’s always a “better” way of doing it. As with Perl, I feel that while I may be a competent Ruby programmer, I’ll never be a Ruby guru (I think that may be the case of many Rails developers : they use Rails and its plugins without really needing to understand Ruby at any deeper level, thanks to Rails’ DSLs). However, the lack of a compelling framework, which would give me the same kind of productivity as Rails, has held me back from using Python for serious web projects.

Until I found Pylons. Unlike Rails and Django, Pylons is not marketed in any way; it is strictly minimalist, a “hacker’s framework”. This will not appeal to those who turn to Rails or Django for an out of the box solution with their decisions made for them (and nothing wrong with that, if you just want to get your project out the door), but it appeals to someone who enjoys building something just the way they want it, and dislikes “opinionated” frameworks that like to think they always know better.

Superficially, Pylons resembles Rails: it follows the same MVC pattern, supports AJAX, and uses Routes and helpers. That’s where the similarity ends. For starters, there’s no ActiveRecord: you provide your own model; most Pylons developers go with SQLAlchemy, possibly one of the finest ORMs in any language. Further, rather than just ERB on the menu, you can choose your own template engine. Myghty is the current default, but this is soon to be replaced with the awesome Mako, and you can use for example Genshi or Kid if you prefer something more XML-based, or Jinja if you like Django’s minimalist templates.

The most interesting thing about Pylons however is that it runs on Paste and WSGI, the Python web server gateway standard. You can run your Pylons apps on mod_python, FastCGI, SCGI, whatever you want, and build your own custom frameworks with Paste templates.

I can’t remember where I saw the quote, but David Heinemeier Hansson, the leading Rails developer, once compared Rails to a Ferrari. Well, a Ferrari is nice (and maybe not the best comparison, considering the performance of Ruby) but Pylons + SQLAlchemy + Mako is more like James Bond’s Aston Martin, customized by Q. It just looks like a normal car but comes with ejector seats, bulletproof glass and tons of gadgets. I know which one I’d like to drive.