jinja2宏中的* args,** kwargs [英] *args, **kwargs in jinja2 macros

查看:108
本文介绍了jinja2宏中的* args,** kwargs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多余的参数如何?为Jinja2宏处理的kwarg?该文档不是一目了然.

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 %}

这将导致

jinja2.exceptions.TemplateSyntaxError

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

文档说:

虚假

类似于 varargs ,但用于关键字参数.所有未使用的关键字参数都存储在此特殊变量中.

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'

我没有示例,也没有在Jinja2源代码atm中开玩笑.目前,文档尚不清楚.任何想法表示赞赏.

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.

推荐答案

诀窍在于,必须至少在应该接受kwargs的任何宏中对kwargs进行一次访问.也就是说,必须在宏主体中调用{{ kwargs }}一次,而无需在宏参数列表中声明它.对于{{ varargs }}也是一样.

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 }}.

这不起作用

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

这将

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

这篇关于jinja2宏中的* args,** kwargs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆