Twig: in_array or similar possible within if statement

twig

I am using Twig as templating engine and I am really loving it. However, now I have run in a situation which definitely mustbe accomplishable in a simpler way than I have found.

What I have right now is this:

{% for myVar in someArray %}    
    {% set found = 0 %}
    {% for id, data in someOtherArray %}
        {% if id == myVar %}
            {{ myVar }} exists within someOtherArray.
            {% set found = 1 %} 
        {% endif %}
    {% endfor %}

    {% if found == 0 %}
        {{ myVar }} doesn't exist within someOtherArray.
    {% endif %}
{% endfor %}

What I am looking for is something more like this:

{% for myVar in someArray %}    
    {% if myVar is in_array(array_keys(someOtherArray)) %}
       {{ myVar }} exists within someOtherArray.
    {% else %}
       {{ myVar }} doesn't exist within someOtherArray.
    {% endif %}
{% endfor %}

Is there a way to accomplish this which I haven't seen yet?

If I need to create my own extension, how can I access myVar within the test function?

Thanks for your help!

Best Answer

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.

Related Topic