* args, ** kwargs in jinja2 macros

How are additional arguments and kwargs handled for the Jinja2 macro? The documentation is not entirely clear.

For example, this is clearly not true:

{% macro example_1(one, two, **kwargs) %} do macro stuff {% endmacro %} 

that leads to

 jinja2.exceptions.TemplateSyntaxError TemplateSyntaxError: expected token 'name', got '**' 

The documentation says:

kwargs

Like varargs, but for keyword arguments. All unused keyword arguments are stored in this special variable.

Unfortunately, any combo of additional keyword arguments is a mistake,

 {% macro example_2(one, two) %} do macro stuff {% endmacro %} {{ example_2(one, two, test='test') }} TypeError: macro 'example_2' takes no keyword keyword argument 'test' 

I have no examples, and I don't get stuck in the Jinja2 atm source code. Currently, the documentation is not clear to me. Any thoughts appreciated.

+47
macros python jinja2
Dec 19 '12 at 2:35
source share
1 answer

The trick is that kwargs should be available at least once in any macro that should accept them. In other words, you should call {{ kwargs }} once in a macro object without declaring it in the macro argument list. The same is true for {{ varargs }} .

This will not work

 {% macro example_2(one, two) %} * {{one}} - {{two}} {% endmacro %} {{example_2(1, 2, test="Hello")}} 

This will

 {% macro example_2(one, two) %} * {{one}} - {{two}} * {{kwargs}} {% endmacro %} {{example_2(1, 2, test="Hello")}} 
+56
Dec 19 '12 at 3:05
source share



All Articles