Jinja2模板设计文档—测试器

Beside filters, there are also so-called “tests” available. Tests can be used to test a variable against a common expression. To test a variable or expression, you add is plus the name of the test after the variable. For example, to find out if a variable is defined, you can do name is defined, which will then return true or false depending on whether name is defined in the current template context.

除了过滤器,这里有一个称为“测试器”(tests)的可以使用。测试器可以通过一个常规表达式测试一个变量。如果想测试一个变量或者表达式,您只需要在变量之后添加is和测试器名称。例如,为了确定变量是否被定义,可以这样做name is defined 。这样,该表达式将会依赖模板上下文中是否定义了变量name而返回true和false。

Tests can accept arguments, too. If the test only takes one argument, you can leave out the parentheses. For example, the following two expressions do the same thing:

测试器也可以接受参数。如果测试器仅仅接受一个参数,您可以不使用圆括号。例如,如下两个表达式是等效的:

{% if loop.index is divisibleby 3 %}
{% if loop.index is divisibleby(3) %}

The List of Builtin Tests below describes all the builtin tests.

内建测试器列表描述了了所有的内建测试器。

如果引用本站的原创文章,请注明原文链接:,本站保留追究责任的权利!