Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last iteration on For loop with If condition with twig

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.

like image 778
Vladimir-Manov Avatar asked Jan 27 '23 04:01

Vladimir-Manov


2 Answers

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

like image 151
Matteo Avatar answered Jan 30 '23 03:01

Matteo


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(',') }}
like image 41
user9189147 Avatar answered Jan 30 '23 05:01

user9189147