ServerSideSkittles ServerSideSkittles - 2 months ago 26
Twig Question

Twig check if value in array is true

I have an array which contains booleans. How do I search the array to see if one or more is true and then display the something once?

Here is my code so far

{% set guides =
[
product.is_user_guide,
product.is_product_guide,
product.is_installation_guide
]
%}

{% for guide in guides %}
{% if (guide) %}
<h1>There is a guide!</h1>
{% endif %}
{% endfor %}


In the above code it finds 2 values in the array to true and displays the h1 twice. How can I modify it so it only displays once?

Answer

You can use the containment operator in:

{% set guides = [
    product.is_user_guide,
    product.is_product_guide,
    product.is_installation_guide
] %}

{% if true in guides %}
   <h1>There is a guide!</h1>
{% endif %}

Demo: http://twigfiddle.com/pf4xjp

Comments