Jinja2 filter to find out is any value from a list matches with any value from another list

67 views Asked by At

I am looking for the way to perform the following filter and test without using any custom filters (just built-in filters only)?

list1 = ['playing', 'off', 'off', 'off']
list2 = ['off', 'idle', 'paused']

I got these two lists and want to have a single line filter test where the result will be True or False. True if all items from list1 matches with list2 and False if at least one or more items from list1 does not matches with list2.

# Example - 1:
list1 = ['playing', 'off', 'off', 'off']
list2 = ['off', 'idle', 'paused']    
result = False

# Example - 2:
list1 = ['playing', 'off', 'playing', 'off']
list2 = ['off', 'idle', 'paused']    
result = False

# Example - 3:
list1 = ['idle', 'off', 'paused', 'off']
list2 = ['off', 'idle', 'paused']    
result = True
1

There are 1 answers

0
t.abraham On

Finally found the solution. The use of reject() filter solved it

{{ True if (list1 | reject('in', list2) | list | count) == 0 else False }}

this filter gives out the desired output

# Example - 1:
list1 = ['playing', 'off', 'off', 'off']
list2 = ['off', 'idle', 'paused']    
result = False

# Example - 2:
list1 = ['playing', 'off', 'playing', 'off']
list2 = ['off', 'idle', 'paused']    
result = False

# Example - 3:
list1 = ['idle', 'off', 'paused', 'off']
list2 = ['off', 'idle', 'paused']    
result = True