Let's assume I have an array $cars
where $cars = [$toyota, $vw]
and
$toyota= [
'id' => 1,
'color' => 'green',
];
$vw= [
'id' => 7,
'color' => 'red',
];
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]
).
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.
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. 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..
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…