检查树枝是否在给定数组中至少存在on属性 [英] Check in twig if at least on property exists in a given array

查看:50
本文介绍了检查树枝是否在给定数组中至少存在on属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组 $ cars ,其中 $ cars = [$ toyota,$ vw]

Let's assume I have an array $cars where $cars = [$toyota, $vw] and

$toyota= [
    'id' => 1,
    'color' => 'green',
  ];

$vw= [
    'id' => 7,
    'color' => 'red',
  ];

我想在 twig 中进行检查,以查看至少一个汽车ID是否存在于专用数组中( [3,,7,15] ).

I wanna do a check in twig to see if at least one of the cars ID exists in a dedicated array ([3, ,7, 15]).

执行此操作的最佳方法是什么?进行 for 循环并不理想,因为如果我发现第一个符合条件的元素,则无法进行 break .如果两个元素都满足条件,我也不想打印两次文本.如果有一个元素,我只想打印文本.

What's the best way to do this? Doing a for loop is not ideal since I cannot do a break if I found the first element matching my criteria. And I also don't wanna print a text twice if both elements satisfy the condition. I just want to print a text if one element does.

我尝试做一些奇怪的事情 {%,如果汽车在[3,7,15]%}中.... {%endif%} ,但是如果明显地行不通,因为我需要检查 id 是汽车,而不是物体...

I tried doing something weird like {% if cars in [3, 7, 15] %} .... {% endif %} but if obvously doesn't work since I need to check the id of a car, not the object...

对于如何最好地解决此问题的任何建议,我们深表感谢.

Any suggestions on how to best solve this is much appreciated.

P.S.我知道在控制器中使用 array_filter 会使它变得更加容易,但可惜的是这对我不起作用.那是因为我使用AJAX,并且在提交后,我将不再有权使用 cars .因此,我需要在视图中执行此操作.

P.S. I know using array_filter in the controller makes it much easier, but sadly that doesn't work for me. That's because I use AJAX and after a submit, I won't have access to cars anymore. Therefore, I need to do it in the view..

推荐答案

只需将新过滤器添加到 twig

Just add a new filter to twig

$twig = new Twig_Environment($loader);

$twig->addFilter(new Twig_SimpleFilter('has', function($haystack, $needles) {
    if (!is_array($needles)) $needles = [ $needles, ];
    return count(array_intersect($haystack, $needles)) > 0;
});

然后您可以在 twig

{% set data = [ 'foo', 'bar', 'foobar', 'lorem', 'lipsum' ] %}
{% if data | has('foo') %}
    data contains foo
{% endif %}

{% if data | has(['lorem', 'lipsum', 'boat']) %}
    data contains lorem, lipsum or boat
{% endif %}

这篇关于检查树枝是否在给定数组中至少存在on属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆