在Jinja2中,如何测试变量是否未定义?

fre*_*ley 166 jinja2

从Django转换,我习惯做这样的事情:

{% if not var1 %} {% endif %}
Run Code Online (Sandbox Code Playgroud)

如果我没有将var1放入上下文中,并使其工作.Jinja2给了我一个未定义的错误.是否有简单的说法{% if var1 == None %}或类似方式?

Gar*_*ett 290

来自Jinja2 模板设计器文档:

{% if variable is defined %}
    value of variable: {{ variable }}
{% else %}
    variable is not defined
{% endif %}
Run Code Online (Sandbox Code Playgroud)

  • 另外,你可以使用`{%if if variable not defined%}`来测试逆. (12认同)
  • `{% if variable is defined and variable %}` 也会检查是否为空 (6认同)
  • @dannyman也许那是因为ansible模板是jinja2? (3认同)

小智 30

{% if variable is defined %}如果变量是,则为true None.

由于not is None不允许,这意味着

{% if variable != None %}

真的是你唯一的选择.

  • 如果要检查“None”,请使用小写的“none”“{% if variable is not none %}” (4认同)
  • @ryanwebjackson 这是名为“none”的[内置测试](https://jinja.palletsprojects.com/en/2.11.x/templates/#none)。 (3认同)
  • @FelipeAlvarez 你有这方面文档的链接吗?提前致谢。 (2认同)

Mic*_*d a 12

您可以使用 Jinja Elvis 运算

{{ 'OK' if variable is defined else 'N/A' }}
Run Code Online (Sandbox Code Playgroud)

或另外检查空置情况

{{ 'OK' if (variable is defined and variable) else 'N/A' }}
Run Code Online (Sandbox Code Playgroud)

Jinja 模板 - 模板设计器文档


fre*_*ley 11

在环境设置中,我们已经undefined = StrictUndefined阻止将未定义的值设置为任何值.这解决了它:

from jinja2 import Undefined
JINJA2_ENVIRONMENT_OPTIONS = { 'undefined' : Undefined }
Run Code Online (Sandbox Code Playgroud)


cze*_*asz 11

你也可以在jinja2模板中定义一个变量,如下所示:

{% if step is not defined %}
{% set step = 1 %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

然后您可以像这样使用它:

{% if step == 1 %}
<div class="col-xs-3 bs-wizard-step active">
{% elif step > 1 %}
<div class="col-xs-3 bs-wizard-step complete">
{% else %}
<div class="col-xs-3 bs-wizard-step disabled">
{% endif %}
Run Code Online (Sandbox Code Playgroud)

否则(如果你不会使用{% set step = 1 %})上面的代码将抛出:

UndefinedError: 'step' is undefined
Run Code Online (Sandbox Code Playgroud)


Lub*_*rga 6

如果您需要,请考虑使用默认过滤器。例如:

{% set host = jabber.host | default(default.host) -%}
Run Code Online (Sandbox Code Playgroud)

或者在末尾使用更多带有“硬编码”的回退值,例如:

{% set connectTimeout = config.stackowerflow.connect.timeout | default(config.stackowerflow.timeout) | default(config.timeout) | default(42) -%}
Run Code Online (Sandbox Code Playgroud)