Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig: in_array or similar possible within if statement?

Tags:

twig

You just have to change the second line of your second code-block from

{% if myVar is in_array(array_keys(someOtherArray)) %}

to

{% if myVar in someOtherArray|keys %}

in is the containment-operator and keys a filter that returns an arrays keys.


Just to clear some things up here. The answer that was accepted does not do the same as PHP in_array.

To do the same as PHP in_array use following expression:

{% if myVar in myArray %}

If you want to negate this you should use this:

{% if myVar not in myArray %}

Try this

{% if var in ['foo', 'bar', 'beer'] %}
    ...
{% endif %}

another example following @jake stayman:

{% for key, item in row.divs %}
    {% if (key not in [1,2,9]) %} // eliminate element 1,2,9
        <li>{{ item }}</li>
    {% endif %}
{% endfor %}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!