Reputation: 71
So this is only an example of what I'm trying to achieve. I'm looping through all items and print only those, who starts with F and separate them with comma.So in the end, the loop will made, for example 15 iterations, but will print only 5.I'm trying to catch the last one that will be printed, so I can remove the comma.I tried with the filter loop.last, but it works only if the loop print the last item, but if the last print was earlier, it's still with comma.
{% for item in items %}
{% if item starts with 'F' %}
{{ item }},
{% endif %}
{% endfor %}
I can't edit anything from items. Please help, I'v been stuck on this from a while.
Upvotes: 6
Views: 22619
Reputation: 39390
A more simply solution could be Adding a condition to the for statement and display the comma only if is not the first interaction (loop.last
is defined when using loop conditions). As example:
{% set items = ['Fitem1', 'item2', 'Fitem3', 'Fitem4', 'item5'] %}
{% for item in items if item starts with 'F'%}
{% if loop.first == false %},{% endif%}
{{item}}
{% endfor %}
See this twigfiddle for the working solutions
Upvotes: 10
Reputation: 296
I tested this, so I thought I would provide an answer:
{% set items = ['Fitem1', 'item2', 'Fitem3', 'Fitem4', 'item5'] %}
{% set newArray = [] %}
{% for item in items %}
{% if item starts with 'F' %}
{% set newArray = newArray|merge([item]) %}
{% endif %}
{% endfor %}
{{ newArray|join(',') }}
Upvotes: 3