Twig check multiple values

2019-07-13 10:20发布

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

2条回答
太酷不给撩
2楼-- · 2019-07-13 10:54

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 %}
查看更多
冷血范
3楼-- · 2019-07-13 11:10

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

查看更多
登录 后发表回答