Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jinja2 macros vs jsp2.0 tags

I am a java programmer learning python/jinja.

My biggest beef with jinja2 macros is the limitation of having a single caller(). for example, i could do the following in jsp2 tags:

tag def:

<% attribute name="title" fragment="true">
<div class='title'>${title}</div>
<div class='body'><jsp:doBody/></div>

usage:

<myTag>
  <jsp:attribute name='title'>
    <c:if test='${blah}'>This is only here sometimes</c:if>
  </jsp:attribute>
  <jsp:body>
    <c:if test='${something}'>some dynamic content</c:if>
  </jsp:body>
</myTag>

what i want to stress here, is that both the body content and the 'title' attribute have content that is dynamic. also, there are no hacks here of setting variables to dynamic content and passing them in.

now lets look at a jinja macro that does the same thing:

{% macro myTag(title='', caller) -%}
  <div class='title'>{{ title }}</div>
  <div class='body'>{{ caller() }}</div>
{%- endmacro %}

but wait! i cannot easily put dynamic content into the title attribute!

{% call myTag(title='imagine putting some content here that involves 5 loops, 4 ifs and whatnot?') %}
   {% if something %}some dynamic content{% endif %}
{% endcall %}

is this a problem with my being a newbie, or is this a shortcoming of jinja?

like image 421
mkoryak Avatar asked Dec 13 '22 08:12

mkoryak


1 Answers

So in fact this is a core feature of Mako Templates for Python. It's not as widely used of a feature but it's important to me, as it's pretty critical in custom template tags as you mention, so it's there:

http://www.makotemplates.org/docs/defs.html#calling-a-def-with-embedded-content-and-or-other-defs

JSP is one of several template systems Mako draws inspiration from.

like image 58
zzzeek Avatar answered Dec 14 '22 21:12

zzzeek