Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if array has more elements in twigs for loop?

Tags:

twig

symfony

I am currently concatenating array elements in a single variable with , between them. I'm getting record like this

abc,def,ghi, 

I dont want to add an extra comma , after last element. My code is:

{% for driver in item.vehicles if driver.driver.firstName %}
{% set isDriver = 1 %}
{% set driverList = driverList ~ driver.driver.firstName ~ ',' %}
{% endfor %}
 
like image 677
Umair Malik Avatar asked Dec 19 '22 03:12

Umair Malik


1 Answers

You can use the TWIG LOOP VARIABLE for your needed like this:

{% for driver in item.vehicles if driver.driver.firstName %}
{% set isDriver = 1 %}
{% set driverList = driverList ~ driver.driver.firstName  %}

   {% if loop.last == false %}
   {% set driverList = driverList ~  ',' %}
   {% endif %}

{% endfor %}
like image 172
jack Avatar answered Mar 25 '23 00:03

jack