Jinja2 default( ) Test

Example #1

Reference: Jinja

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

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

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:

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:

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

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:

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

Knowledge Base

See the Ansible section of my Knowledge Base for more information.

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 Twitter (@OzNetNerd).

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