*args, **kwargs 在 jinja2 宏中

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

问题描述

额外的参数如何?为 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 宏中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)