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

4.1k views Asked by At

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 %}
 
4

There are 4 answers

1
Med On

Just test for the last loop index

{% for driver in item.vehicles if driver.driver.firstName %}
    {% set isDriver = 1 %}
    {% if loop.index is not sameas(loop.last)  %}
        {% set driverList = driverList ~ driver.driver.firstName ~ ',' %}
    {%else%}
        {% set driverList = driverList ~ driver.driver.firstName  %}
    {%endif%}
{% endfor %}
3
jack On

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 %}
0
qooplmao On

Rather than counting the loop you could just create an array of drivers and join them with a , like..

{% set driverList = [] %}
{% for driver in item.vehicles if driver.driver.firstName %}
    {% set driverList = driverList|merge([driver.driver.firstName]) %}
{% endfor %}
{{ driverList|join(',') }}
0
shrty On

The loop.length, loop.revindex, loop.revindex0, and loop.last variables are only available for PHP arrays, or objects that implement the Countable interface. They are also not available when looping with a condition.

http://twig.sensiolabs.org/doc/2.x/tags/for.html

You could just do this (if you like to style the name with a link, you should set it to a variable)

{% for driver in item.vehicles if driver.driver.firstName %}
  {{ loop.index > 1 ? ', ': ''}}{{ driver.driver.firstName }}
{% endfor %}