Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Twig 如果给定数组中至少存在on属性,请签入细枝_Twig_Frontend - Fatal编程技术网

Twig 如果给定数组中至少存在on属性,请签入细枝

Twig 如果给定数组中至少存在on属性,请签入细枝,twig,frontend,Twig,Frontend,假设我有一个数组$cars,其中$cars=[$toyota,$vw]和 $toyota= [ 'id' => 1, 'color' => 'green', ]; $vw= [ 'id' => 7, 'color' => 'red', ]; 我想在细枝中进行检查,查看专用数组中是否至少存在一个汽车ID([3,7,15]) 最好的方法是什么?执行for循环并不理想,因为如果发现第一个元素与我的条件匹配,我就无法执行中断。如果两个元

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

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

$vw= [
    'id' => 7,
    'color' => 'red',
  ];
我想在
细枝中进行检查,查看专用数组中是否至少存在一个汽车ID(
[3,7,15]

最好的方法是什么?执行
for
循环并不理想,因为如果发现第一个元素与我的条件匹配,我就无法执行
中断。如果两个元素都满足条件,我也不想打印两次文本。我只想打印一个文本,如果有一个元素

我试着做一些奇怪的事情,比如
{%if汽车在[3,7,15]]}。。。。{%endif%}
但如果由于我需要检查汽车的
id
,而不是对象,因此显然不起作用

任何关于如何最好地解决这一问题的建议都将不胜感激


另外,我知道在控制器中使用
array\u filter
会更容易,但遗憾的是,这对我不起作用。这是因为我使用AJAX,提交后,我将无法再访问
cars
。因此,我需要在视图中执行此操作。

您可以执行以下操作(请参阅):


但是,即使这是一个有效的解决方案,您也可以在PHP代码中实现它,并将这样的函数公开为。

只需向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_环境($loader)是什么
表示加载程序
来自何处。在哪个上下文中使用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 %}