5

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

4 Answers 4

6

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 %}
Sign up to request clarification or add additional context in comments.

3 Comments

tried but it didn't heleped :( its still concatenating , with string.
it is also giving error “The “loop.last” variable is not defined when looping with a condition. I tried adding driver in place of loop but by that way it always come inside if condition
Hi @UmairMalik very strange... i recently used this statement: {% if not loop.last %} try this approach, let me know is this is good for you i will update my answer.
3

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(',') }}

Comments

2

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

1 Comment

thanks Med for your time, i tried your code it's not coming inside if condition
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.