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

当前回答

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

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

其他回答

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

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

{{ variable or '' }}

为了避免在"p"或"p. user "为None时抛出异常,您可以使用:

{{ (p and p.User and p.User['first_name']) or "default_value" }}

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

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

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

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

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