Jinja call Block with Arguments
n
The call block in Jinja2 becomes incredibly powerful when it receives arguments from the macro it calls. This enables you to create dynamic components where the macro controls the flow (e.g., a loop) and the call block provides the custom rendering logic for each item.
nn
How it Works
n
When using arguments, the macro calls the special `caller()` variable and passes the argument(s) to it, like `{{ caller(user) }}`. The call block then defines the arguments it expects to receive in its opening tag, for example, `{% call(user) … %}`. The inner content of the call block can then access these arguments, allowing you to define the layout for each item returned by the macro.
nn
nn
Code Demonstration
n
The following example demonstrates how a macro iterates over a list of users and passes each user object to the call block for custom rendering.
nn
Macro Definition
n
{% macro dump_users(users) -%}n <ul>n {%- for user in users %}n <li><p>{{ user.username|e }}</p>{{ caller(user) }}</li>n {%- endfor %}n </ul>n{%- endmacro %}
n
Call Block Usage
n
{% call(user) dump_users(list_of_user) %}n <dl>n <dt>Realname</dt>n <dd>{{ user.realname|e }}</dd>n <dt>Description</dt>n <dd>{{ user.description }}</dd>n </dl>n{% endcall %}
n
The `(user)` in the call block tag is what enables it to receive the `user` object from the macro and use it to render the custom description list for each item in the loop.
nn
n
n
