如何使一个变量在jijna2默认为“”如果对象是None而不是这样做?

      {% if p %}   
        {{ p.User['first_name']}}
      {% else %}
        NONE
      {%endif %}

所以如果对象p是None,我想默认值p (first_name和last_name)为“”。 基本上

nvl(p.User[first_name'], "")

错误接收:

Error:  jinja2.exceptions.UndefinedError
    UndefinedError: 'None' has no attribute 'User'

当前回答

从Ansible 2.8开始,你可以使用:

{{ p.User['first_name'] }}

看到https://docs.ansible.com/ansible/latest/porting_guides/porting_guide_2.8.html jinja-undefined-values

其他回答

使用none测试(不要与Python的none对象混淆!):

{% if p is not none %}   
    {{ p.User['first_name'] }}
{% else %}
    NONE
{% endif %}

or:

{{ p.User['first_name'] if p is not none else 'NONE' }}

或者如果你需要一个空字符串:

{{ p.User['first_name'] if p is not none }}

从Ansible 2.8开始,你可以使用:

{{ p.User['first_name'] }}

看到https://docs.ansible.com/ansible/latest/porting_guides/porting_guide_2.8.html jinja-undefined-values

你可以简单地添加"default none"到你的变量中,如下所示:

{{ your_var | default('NONE', boolean=true) }}

按照这个文档,你可以这样做:

{{ p.User['first_name']|default('NONE') }}

如果你想设置自己的默认值而不是None,那么就简单地这样做

{{your_var |默认值:“缺省名称}}