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

当前回答

我通常定义一个nvl函数,并把它放在全局变量和过滤器中。

def nvl(*args):
    for item in args:
        if item is not None:
            return item
    return None

app.jinja_env.globals['nvl'] = nvl
app.jinja_env.filters['nvl'] = nvl

模板中的用法:

<span>Welcome {{ nvl(person.nick, person.name, 'Anonymous') }}<span>

// or 

<span>Welcome {{ person.nick | nvl(person.name, 'Anonymous') }}<span>

其他回答

使用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.User['first_name']|default('NONE') }}

通过ChainableUndefined,你可以做到这一点。

>>> import jinja2
>>> env = jinja2.Environment(undefined=jinja2.ChainableUndefined)
>>> env.from_string("{{ foo.bar['baz'] | default('val') }}").render()
'val'

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

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

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