'empty()' Jinja test?

10,387 views
Skip to first unread message

Dmitry Makovey

unread,
Nov 20, 2014, 2:22:00 PM11/20/14
to ansible...@googlegroups.com
Hi,

several times now I came across situation where one of the modules returns 'empty list' in variable and it would be handy to have a simple test like:

{% if foo is empty %}

which is not the same as

{% if foo is defined %} 

because former case covers also "", [], {} and None as well as "undefined". Sort of like "empty()" call in PHP.

Right now I've been managing situation with crutches like:

when: foo_list|join('') != ''

but that is non-descriptive and hackish IMO. Is there an interest of adding this feature? Shall I post into Github issue tracker?

Brian Coca

unread,
Nov 20, 2014, 3:02:43 PM11/20/14
to ansible...@googlegroups.com
would this not work?
foo|length == 0
> --
> You received this message because you are subscribed to the Google Groups
> "Ansible Project" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to ansible-proje...@googlegroups.com.
> To post to this group, send email to ansible...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/ansible-project/9d9f8ef2-87df-4a50-80c9-eec1cb1e84e1%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



--
Brian Coca

Matt Martz

unread,
Nov 20, 2014, 3:18:05 PM11/20/14
to ansible...@googlegroups.com
Since jinja2 uses python under the hood, you get the benefit of python truthiness checks.  I would probably write this as:

{% if foo is defined and foo %}

In some cases this can be shortened to just:

{% if foo %}

The inverse to see if it is empty is:

{% if not foo %}



For more options, visit https://groups.google.com/d/optout.



--
Matt Martz
@sivel
sivel.net
Reply all
Reply to author
Forward
0 new messages