Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "if any():" in Jinja2?

In Jinja2 I'm looking for a way to check if at least one of a list of variables has a value. Basically in python I would do:

if any([item['genre'], item['type'], item['color']]):

However, in Jinja the following isn't valid:

{% if any([item['genre'], item['type'], item['color']]) %}
# some part of the Jinja template
{% endif %}

Is there a way to have the same "any()" check in Jinja2?

For background: the full piece of code that I currently try to add (but isn't valid):

{% if any([item['genre'], item['type'], item['color']]) %}
<ItemProperties>
    <ItemProperty key="genre">{{ item['genre'] }}</ItemProperty>
    <ItemProperty key="type">{{ item['type'] }}</ItemProperty>
    <ItemProperty key="color">{{ item['color'] }}</ItemProperty>
</ItemProperties>
{% endif %}
like image 991
KCDC Avatar asked Feb 07 '19 14:02

KCDC


People also ask

How do you write if condition in Jinja?

How do you write if condition in Jinja? {% if %} with {% elif %} {% else %} . - The {% if %} statement is the primary building block to evaluate conditions. The {% if %} statement is typically used in conjunction with the {% elif %} and {% else %} statements to evaluate more than one condition.

How do you write a for loop in Jinja2?

Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.

How do you call a Python function in Jinja2?

globals to call a function in a jinja2 template. Create a format string that applies a function by calling "{{ func(input) }}" apply the function func to input . Call jinja2. Template(s) , where s is the previous result to create a new jinja2.


1 Answers

There is no direct equivalent of the any() function in Jinja2 templates.

For 3 hard-coded elements, I'd just use boolean logic or:

{% if item['genre'] or item['type'] or item['color'] %}

Otherwise, you can use the select() filter without an argument (followed by first() to force iteration). Because select() is itself a generator, using first() on select() makes this short-circuit the way any() would:

{% if (item['genre'], item['type'], item['color'])|select|first %}

Without an argument, select() returns any objects from the input sequence that are true, and first() ensures it iterates no more than needed to find one such element.

The last option is to register a custom filter to just add any() to Jinja yourself; I'd also add all() in that case. You can register both functions directly, since neither takes options:

environment.filters['any'] = any
environment.filters['all'] = all

at which point you can then use

{% if (item['genre'], item['type'], item['color'])|any %}
like image 143
Martijn Pieters Avatar answered Sep 29 '22 21:09

Martijn Pieters