问题描述
额外的参数如何?为 Jinja2 宏处理的 kwargs?文档不是很清楚.
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 '**'
文档说:
kwargs
类似于 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 }}
,而不是在宏参数列表中声明它.{{ 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")}}
这篇关于*args, **kwargs 在 jinja2 宏中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!