I’ve done a few small-ish Django projects, and each time I’ve been struck by the apparent limitations of Django’s templating language. Just as a random example, I was shocked to learn that if, in the context of a template, I had a variable bar and a dict foo, I couldn’t access foo[bar] unless I wrote my own filter to do it.
I’ve read that the reason for this is because Django was created for environments where the people designing the pages were not programmers. I understand that.
But let’s say that’s not a problem for me. Is there a reason why I should stick with Django’s templating language, rather than switching over to something with a lot more power, like Mako (where you can even execute arbitrary Python expressions)?
I had the opportunity to use Mako for a school project a while back, and I really loved the power of it. For example, as part of the project, we had to make a big table, where building each row and cell was fairly complex. Yet, I could make my template look something like:
<table>
% for foo in foos:
${makerow(row)}
% endfor
</table>
<%def name="makerow(row)">
<tr>
# Blah blah blah (possibly a call to makecell somewhere)
</tr>
</%def>
Maybe this is a violation of separation of presentation and logic, but boy is it nice and clean. Subroutines! Abstraction! Good stuff.
And a follow-up question: If using an alternative templating language isn’t frowned upon by the Django community, does anyone have any to suggest? Like I said, I really like Mako, but it’s literally the only one I’ve used other than Django’s.
I’ll be honest, I didn’t thoroughly read the responses. But I’m guessing it’s a lot of “no python in your templates” and “your view shouldn’t have much logic” type stuff.
If you put idealism aside and opt for pragmatism then I think Mako is a fine choice. I’m using it in a production capacity (mainly for speed, power and dynamic inheritance) for 3+ years now. It hasn’t failed or been otherwise annoying in any way.
The idealists are correct, but sometimes you have to go for what’s doable vs what’s right. If you are not limited by the Django templating engine use it. If you need more power, Mako and Jinja are fine choices.
Django makes it very easy to swap out templating engines and keep most things working as before:
http://docs.djangoproject.com/en/dev/ref/templates/api/#using-an-alternative-template-language