Twig check multiple values

2019-07-13 10:16发布

问题:

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"?

回答1:

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 %}

fiddle



回答2:

Digging deeper in Twig, I would do like this...

{% set has_color = false %}
{% for color in product if color is true %}
   {% set has_color = true %}
{% endfor %}

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