如果给定数组中至少存在一个属性,则检查 twig [英] Check in twig if at least on property exists in a given array
问题描述
假设我有一个数组 $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.
我试着做一些奇怪的事情,比如{% if cars in [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.
附:我知道在控制器中使用 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 %}
这篇关于如果给定数组中至少存在一个属性,则检查 twig的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!