Twig: loop.last missing when applying filter
Hi,
It seem that the property loop.last disappear from the properties of the loop object when we apply a filter on the loop.
Here is the code I use :
{% for payment in payments | filter(p => p.enabled) %}
{{ ('global.payment_type.' ~ payment.name) | trans }}
{% if not loop.last %}
<br/>
{% endif %}
{% endfor %}
This code crash because the property loop.last doesn’t exists. But if you remove the filter at the beginning of the loop, the property loop.last is back again.
The same problem occur if we filter the list before and loop on it :
{% set filteredPayments = payments | filter(p => p.enabled) %}
{% for payment in filteredPayments %}
{{ ('global.payment_type.' ~ payment.name) | trans }}
{% if not loop.last %}
<br/>
{% endif %}
{% endfor %}
Again, crash due to the missing loop.last.
I am on Symfony 4.4.5 with twig/twig 3.0.3.
Is it a restriction like the old for…if ? If I remember well, the usage of filter should have fixed it.
I can still count the number of items in the filtered list first and check with the loop.index0, but it’s the exact reason for the existence of loop.last.
Any idea why it disappear with filtered list ?
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 3
- Comments: 15 (8 by maintainers)
@djpretzel yes indeed. and if
artistshas a single item each time, you will indeed always be on the first iteration of the loop (the inner one, which is the active one). My guess is that yourProticityandzykOartists are belong to differentalbum_tracks_artistfor the iteration of the outer loop.