ServerSideSkittles ServerSideSkittles - 1 year ago 201
Twig Question

Twig check multiple values

I have about 5 or so tables that are booleans. I want to test all of them and if one or more return true then to do something.

So far I have tried something like

{% if product.is_red == true %}

<h1>Has colors</h1>

{% elseif product.is_yellow == true %}

<h1>Has colors</h1>

{% elseif product.is_green == true %}

<h1>Has colors</h1>

{% elseif product.is_purple == true %}

<h1>Has colors</h1>

{% elseif product.is_black == true %}

{% endif %}

But if anyone of them returns true then it will say

Has Colors

whatever the amount of times it returns true. Is there any way to check all of them and if one more returns true then returns "Has colors"?

Answer Source

You have to work with a flag in twig to keep track if one or more colors are specified. A shorter example of the code would be (should also work with an object product):

    set product = {
        'is_red'     : false,
        'is_yellow'  : false,
        'is_blue'    : true,
        'is_green'   : false,

{% set has_color = false %}
{% for color in ['red', 'yellow', 'blue', 'green', 'purple', ] %}
   {% if product['is_'~color] is defined and product['is_'~color] %}{% set has_color = true %}{% endif %}
{% endfor %}

{% if has_color %}
<h1>Has color</h1>
{% endif %}


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download