Example #1

Reference: Jinja

Syntax:

default(value, default_value=u'', boolean=False)

Example #1

If the value is undefined it will return the passed default value, otherwise the value of the variable:

{{ my_variable|default('my_variable is not defined') }}

This will output the value of my_variable  if the variable was defined, otherwise ‘my_variable is not defined’. If you want to use default with variables that evaluate to false  you have to set the second parameter to true:

{{ ''|default('the string was empty', true) }}

Example #2

Reference: webforefront

The default  or d  filter is used to specify a default value if a variable is undefined or is false (i.e. it doesn’t exist or is empty). For example, the filter statement:

{{variable|default("no value")}}

outputs “no value” only if the variable is undefined, otherwise it outputs the variable value.

Example #3

If in addition you want to provide a default value for a variable that evaluates to false , is None  or is an empty string, you have to add True  as a second filter parameter, e.g:

{{variable|default("no value",true)}}

outputs “no value” if the variable is undefined, false , is None  or is an empty string).


As always, if you have any questions or have a topic that you would like me to discuss, please feel free to post a comment at the bottom of this blog entry, e-mail at will@oznetnerd.com, or drop me a message on Reddit (OzNetNerd).

Note: The opinions expressed in this blog are my own and not those of my employer.

Leave a comment