Jinja2 template variable if None Object set a default value

后端 未结 9 2035
感情败类
感情败类 2020-12-04 08:33

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\'         


        
相关标签:
9条回答
  • 2020-12-04 08:54

    I usually define an nvl function, and put it in globals and filters.

    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
    

    Usage in a template:

    <span>Welcome {{ nvl(person.nick, person.name, 'Anonymous') }}<span>
    
    // or 
    
    <span>Welcome {{ person.nick | nvl(person.name, 'Anonymous') }}<span>
    
    0 讨论(0)
  • 2020-12-04 09:06

    As addition to other answers, one can write something else if variable is None like this:

    {{ variable or '' }}
    
    0 讨论(0)
  • 2020-12-04 09:09
    {{p.User['first_name'] or 'My default string'}}
    
    0 讨论(0)
提交回复
热议问题