Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

frontend - Check in twig if at least on property exists in a given array

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do something like this (see https://twigfiddle.com/8u3eh5):

{% set found = false %}

{% for car in cars %}
    {% if car.id in ids %}
        {% set found = true %}
    {% endif %}
{% endfor %}

{% if found %}
    found
{% else %}
    not found
{% endif %}

However, even if this is a working solution, you will be better off by implementing this in PHP code and expose such a function as a Twig test.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...