240

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!

4

7 回答 7

505

您只需将第二个代码块的第二行从

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

{% if myVar in someOtherArray|keys %}

in是包含操作符,而keys是一个返回数组键的过滤器。

于 2011-09-18T09:25:49.403 回答
123

只是为了清除这里的一些东西。被接受的答案与 PHP in_array不同。

要执行与 PHP in_array相同的操作,请使用以下表达式:

{% if myVar in myArray %}

如果你想否定这个,你应该使用这个:

{% if myVar not in myArray %}
于 2016-05-05T09:45:03.700 回答
33

尝试这个

{% if var in ['foo', 'bar', 'beer'] %}
    ...
{% endif %}
于 2019-02-18T09:30:48.070 回答
10

@jakestayman 之后的另一个例子:

{% for key, item in row.divs %}
    {% if (key not in [1,2,9]) %} // eliminate element 1,2,9
        <li>{{ item }}</li>
    {% endif %}
{% endfor %}
于 2016-05-23T15:11:08.547 回答
4

虽然上面的答案是正确的,但我在使用三元运算符时发现了一些更人性化的方法。

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

如果有人需要通过foreach工作,

{% for attachment in attachments %}
    {{ attachment in item['Attachments'][0] ? 'y' : 'n' }}
{% endfor %}
于 2019-10-02T05:28:08.467 回答
3

它应该可以帮助你。

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

更多信息:http ://twig.sensiolabs.org/doc/tags/for.html

于 2016-07-12T13:30:15.933 回答
0

这些天来,这里有一个用 Twig 的所有可能性来完成答案:

要实现这样的目标:

{% for myVar in someArray %}    
    {% if myVar in someOtherArray|keys %}
       {{ myVar }} exists within someOtherArray.
    {% else %}
       {{ myVar }} doesn't exist within someOtherArray.
    {% endif %}
{% endfor %}

https://twigfiddle.com/0b5crp

您还可以使用数组映射并具有以下单行:
(Twig >= 1.41 或 >= 2.10 或任何 3.x 版本)

{{ someArray|map(myVar => myVar ~ (myVar not in someOtherArray|keys ? ' doesn\'t') ~ ' exists within someOtherArray.')|join('\n') }}

它输出的东西非常相似。

另请参阅此 Twig fiddle:https ://twigfiddle.com/dlxj9g

于 2021-05-28T10:27:56.927 回答