如何使一个变量在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'

当前回答

除了其他答案,如果变量为None,可以写一些其他的东西,像这样:

{{ variable or '' }}

其他回答

{{p.User['first_name'] or 'My default string'}}

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

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

使用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 }}

根据文档,你可以这样做:

{{ p|d('', true) }}

原因None在布尔上下文中转换为False。

作为另一个解决方案(有点类似于之前的一些):

{{ ( p is defined and p.User is defined and p.User['first_name'] ) |default("NONE", True) }}

注意最后一个变量(p.p uuser ['first_name'])后面没有if定义的test。