Jinja2模板变量(如果无对象)设置默认值 [英] Jinja2 template variable if None Object set a default value

查看:608
本文介绍了Jinja2模板变量(如果无对象)设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果对象为None而不是这样做,如何在jijna2中将变量默认设置为"?

How to make a variable in jijna2 default to "" if object is None instead of doing something like this?

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

因此,如果对象p为None,我想将p的值(first_name和last_name)默认设置为". 基本上

So if object p is None I want to default the values of p (first_name and last_name) to "". Basically

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

接收错误:

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

推荐答案

使用 None混淆.对象!):

Use the none test (not to be confused with Python's None object!):

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

或:

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

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

or if you need an empty string:

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

这篇关于Jinja2模板变量(如果无对象)设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆