Mako: def composition (at render time) not evaluating properly

149 views Asked by At

In the process of understanding Mako (template engine for Python), I started playing with defs constructs.

One thing I attempted to do was producing a general "if" statement (say, a JavaScript one) out of def calls. Here's the text:

<%def name="if_statement(x)">if (${x})</%def>
<%def name="sample_condition()">3 == 3</%def>

${if_statement(sample_condition())}

The output is not the expected if(3 == 3), but 3 == 3if(), just like if_statement's argument was evaluated before any other content of the def and rendered at the front.

Is this the expected behavior? And if yes, why? Also, how could I achieve what I was trying to do?

1

There are 1 answers

0
Tupteq On BEST ANSWER

Yes, it's a desired behavior due to buffering, but you can easily get it working as you wanted with use of built-in capture() function. Here's the working example:

<%def name="if_statement(x)">if (${x})</%def>
<%def name="sample_condition()">3 == 3</%def>

${if_statement(capture(sample_condition))}

Result is if (3 == 3).