Another reason to use Mako in Django
I have been contemplating switching to Mako templates for my Django projects for quite some time, partly because I found some of the template syntax in Django slightly awkward.
Today, a question about recursion support in Django templates came up on the #Django IRC channel, which made me think for a minute. Off the top of my head, I couldn’t think of a quick way of accomplishing this in Django, short of using a template tag. However, some examples that I had seen in Mako came to mind, which illustrates the flexibility and power of this templating language.
I decided I would put together some code just to showcase how it could work. The example I chose is to print an organizational chart using the simple Employee class below:
models.py:
class Employee(models.Model):
name = models.CharField(max_length=64)
reports_to = models.ForeignKey('self', related_name='employees')
organizational_chart.html:
<ul>
${render_employee(ceo)}
</ul>
<%def name="render_employee(person)">
<li>${person.name}
<ul>
% for employee in person.employees:
%{render_person(employee)}
% endfor
</ul>
</li>
</%def>
Leave a Reply