Mako or Jinja2?

I did not find a good comparison of jinja2 and Mako. What would you use for what tasks?

I was personally satisfied with mako (in the context of pylons web applications), but I'm curious to find out if jinja2 has any nice features / improvements that mako doesn't have? or maybe cons? -

+43
python template-engine templates jinja2 mako
Aug 08 '10 at 20:35
source share
2 answers

I personally prefer the Jinja2 syntax over Mako. Take this example from the Mako website

<%inherit file="base.html"/> <% rows = [[v for v in range(0,10)] for row in range(0,10)] %> <table> % for row in rows: ${makerow(row)} % endfor </table> <%def name="makerow(row)"> <tr> % for name in row: <td>${name}</td>\ % endfor </tr> </%def> 

There are so many designs here that I would have to consult the documentation before I could even get started. What tags start as <% and close with /> ? Which of them is allowed to close with %> ? Why is there another way to enter the template language when I want to output a variable ( ${foo} )? What is wrong with this artificial XML, where some directives are closed as tags and have attributes?

This is an equivalent example in Jinja2:

 {% extends "base.html" %} <table> {% for row in rows %} {{ makerow(row) }} {% endfor %} </table> {% macro make_row(row) %} <tr> {% for name in row %} <td>{{ name }}</td> {% endfor %} </tr> {% endmacro %} 

Jinja2 has filters that I was told Mako had, but I didn’t see them. Filter functions do not act like regular functions; they accept the implicit first parameter of the filtered value. So in Mako you can write:

 ${escape(default(get_name(user), "No Name"))} 

This is terrible. In Jinja2 you will write:

 {{ user | get_name | default('No Name') | escape }} 

In my opinion, Jinja2 examples are extremely readable. Jinja2 is more regular in that tags start and end in a predictable way, either with {% %} for processing and control directives, or {{ }} for outputting variables.

But these are all personal preferences. I do not know another significant reason to choose Jinja2 over Mako or vice versa. And the pylons are big enough that you can use either!

Update included Jinja2 macros. Although, it seems to me, the Jinja2 example is easier to read and understand. Maco-guiding philosophy: "Python is a great scripting language. Don't reinvent the wheel ... your templates can handle it!" But Jinja2 macros (the whole language, actually) are more like Python, which Mako does!

+37
Aug 08 '10 at 21:14
source share

Take a look at the wheezy.template example:

 @require(user, items) Welcome, @user.name! @if items: @for i in items: @i.name: @i.price!s. @end @else: No items found. @end 

It is optimized for performance (more details here and here ), well tested and documented.

+4
Apr 12 '13 at
source share



All Articles