Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*args, **kwargs in jinja2 macros

How are extra args & kwargs handled for a Jinja2 macro? The documentation isn't exactly clear offhand.

For example, this is clearly wrong:

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

which results in

jinja2.exceptions.TemplateSyntaxError

TemplateSyntaxError: expected token 'name', got '**'

The documentation says:

kwargs

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

Unfortunately, any combo of extra keyword arguments is an error,

{% 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 am not poking about in the Jinja2 source code atm. The documentation isn't clear to me at this point. Any thoughts appreciated.

like image 673
blueblank Avatar asked Dec 19 '12 02:12

blueblank


People also ask

What is a Jinja2 macro?

July 20, 2021. Jinja2 is a popular text templating engine for Python that is also used heavily with Ansible. Many network engineers are familiar with it and with leveraging Jinja2 templates for device configurations.

What is Arg and Kwargs?

*args and **kwargs are special keyword which allows function to take variable length argument. *args passes variable number of non-keyworded arguments and on which operation of the tuple can be performed.

What is Kwargs function?

**kwargs. The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is that the double star allows us to pass through keyword arguments (and any number of them).


1 Answers

The trick is that kwargs has to be accessed at least once in any macro that should accept them. That is to say, you must call {{ kwargs }} once in macro body without declaring it in 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")}}
like image 104
Sean Vieira Avatar answered Oct 27 '22 23:10

Sean Vieira