How can I check if an array has more elements in loops for a loop?
I am currently concatenating array elements into one variable, in between. I get a record like this
abc,def,ghi,
I don't want to add an extra comma ,
after the last item. My code:
{% for driver in item.vehicles if driver.driver.firstName %}
{% set isDriver = 1 %}
{% set driverList = driverList ~ driver.driver.firstName ~ ',' %}
{% endfor %}
source to share
You can use TWIG LOOP VARIABLE for your next:
{% 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 %}
source to share
Instead of reading a loop, you can simply create an array of drivers and concatenate them ,
like ..
{% set driverList = [] %}
{% for driver in item.vehicles if driver.driver.firstName %}
{% set driverList = driverList|merge([driver.driver.firstName]) %}
{% endfor %}
{{ driverList|join(',') }}
source to share
Just check 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 %}
source to share
The variables loop.length, loop.revindex, loop.revindex0, and loop.last are only available for PHP arrays or objects that implement the Countable interface. They are also not available for conditional looping.
http://twig.sensiolabs.org/doc/2.x/tags/for.html
You could just do this (if you like to style the name with reference, you should set it to a variable)
{% for driver in item.vehicles if driver.driver.firstName %}
{{ loop.index > 1 ? ', ': ''}}{{ driver.driver.firstName }}
{% endfor %}
source to share