Jinja Special Macro Variables
n
Inside Jinja2 macros, you have access to three special variables that give you powerful control over dynamic arguments and content. These variables are particularly useful for creating flexible and reusable template components.
nn
varargs and kwargs
n
These variables allow a macro to accept a variable number of arguments, just like in Python. This is ideal for scenarios where you can’t predict all the arguments that will be passed in.
nn
- n
varargs: A list containing all **extra positional arguments** that were not explicitly named in the macro definition.kwargs: A dictionary containing all **extra keyword arguments**. This is perfect for accepting additional HTML attributes.
n
n
n
{% macro tag(name, *varargs, **kwargs) -%}n <{{ name }} {% for key, value in kwargs.items() %}{{ key }}="{{ value }}" {% endfor %}>n {{ varargs|join(', ') }}n </{{ name }}>n{%- endmacro %}
n{{ tag(‘div’, ‘Hello’, ‘World’, id=’main’, class=’container’) }}n
n{# Renders as:n
n
n
n#}n
n
nn
caller
n
The caller variable is a callable macro that holds the content passed to the macro via a {% call %} block. It allows you to wrap a block of template code with a macro’s logic or HTML structure.
nn
{% macro wrap_in_box() -%}
n
A message inside the box:
n{{ caller() }}nn
n
n{%- endmacro %} {% call wrap_in_box() %}n
nThis is the content passed from the caller!n
n{% endcall %}n
n
n
n
