Twig: in_array or similar possible within if state

2020-02-07 14:24发布

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!

标签: twig
6条回答
Animai°情兽
2楼-- · 2020-02-07 14:39

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 %}
查看更多
SAY GOODBYE
3楼-- · 2020-02-07 14:39

It should help you.

{% for user in users if user.active and user.id not 1 %}
   {{ user.name }}
{% endfor %}

More info: http://twig.sensiolabs.org/doc/tags/for.html

查看更多
混吃等死
4楼-- · 2020-02-07 14:40

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 %}
查看更多
The star\"
5楼-- · 2020-02-07 14:42

Try this

{% if var in ['foo', 'bar', 'beer'] %}
    ...
{% endif %}
查看更多
家丑人穷心不美
6楼-- · 2020-02-07 14:50

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.

查看更多
淡お忘
7楼-- · 2020-02-07 14:58

Though The above answers are right, I found something more user-friendly approach while using ternary operator.

{{ attachment in item['Attachments'][0] ? 'y' : 'n' }}

If someone need to work through foreach then,

{% for attachment in attachments %}
    {{ attachment in item['Attachments'][0] ? 'y' : 'n' }}
{% endfor %}
查看更多
登录 后发表回答