Jinja2 template variable if None Object set a default value

后端 未结 9 2034
感情败类
感情败类 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:50

    Following this doc you can do this that way:

    {{ p.User['first_name']|default('NONE') }}
    
    0 讨论(0)
  • 2020-12-04 08:50

    To avoid throw a exception while "p" or "p.User" is None, you can use:

    {{ (p and p.User and p.User['first_name']) or "default_value" }}
    
    0 讨论(0)
  • 2020-12-04 08:50

    As of Ansible 2.8, you can just use:

    {{ p.User['first_name'] }}
    

    See https://docs.ansible.com/ansible/latest/porting_guides/porting_guide_2.8.html#jinja-undefined-values

    0 讨论(0)
  • 2020-12-04 08:52

    According to docs you can just do:

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

    Cause None casts to False in boolean context.


    Update: As lindes mentioned, it works only for simple data types.

    0 讨论(0)
  • 2020-12-04 08:52

    As another solution (kind of similar to some previous ones):

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

    Note the last variable (p.User['first_name']) does not have the if defined test after it.

    0 讨论(0)
  • 2020-12-04 08:54

    Use the none builtin function (http://jinja.pocoo.org/docs/templates/#none):

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

    or

    {{ p.User['first_name'] if p != None else 'NONE' }}
    

    or if you need an empty string:

    {{ p.User['first_name'] if p != None }}
    
    0 讨论(0)
提交回复
热议问题