Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 template variable if None Object set a default value

Tags:

jinja2

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 %}

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 receiving:

Error:  jinja2.exceptions.UndefinedError
    UndefinedError: 'None' has no attribute 'User'
like image 751
mcd Avatar asked Oct 01 '22 23:10

mcd


People also ask

What is the default type of a variable in Jinja?

Default type is Undefined, but there are other types available, StrictUndefined being the most useful one. By using StrictUndefined type we tell Jinja to raise error whenever there's an attempt at using undefined variable.

How to replace an undefined variable with a string in Jinja?

By default, when encountering an evaluation statement with undefined variable Jinja will replace it with an empty string. This often comes as a surprise to people writing their first templates. This behavior can be changed by setting argument undefined, taken by Template and Environment objects, to a different Jinja undefined type.

Where does the data come from in a Jinja2 template?

Jinja2 doesn't care where the data comes from, this could come from JSON returned by some API, be loaded from static YAML file, or simply be a Python Dict defined in our app. All that matters is that we have Jinja template and some data to render it with. We now know what Jinja is and why would one use it.

What is the end template in Jinja?

Our end template can be found below: In Jinja anything found between double opening and double closing curly braces tells the engine to evaluate and then print it. Here the only thing found between curly braces is a name, specifically a variable name.


2 Answers

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 %}

or:

{{ 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 }}
like image 349
tbicr Avatar answered Oct 23 '22 18:10

tbicr


{{p.User['first_name'] or 'My default string'}}
like image 162
Torindo Avatar answered Oct 23 '22 18:10

Torindo