Search code examples
twigtwig-filter

Can't iterate the "filter" filter multiple times


I am trying to assign the result of the "filter" filter (available since Twig 2.10) to a variable so that I can use it multiple times:

{% set filtered = collection|filter(element => element.ok) %}

But unfortunately, if I try to iterate over it multiple times (using the "length" filter counts as such), I get the error

Cannot traverse an already closed generator

after the first one. The error is pretty clear that "filter" actually returns an Generator (which I believe can't be iterated multiple times) and not an array or collection.

The problem is that it makes it impossible to write the following code, for example:

{% if filtered|length > 0 %}
<ul>
  {% for element in filtered %}
      <li>{{ element }}</li>
  {% endfor %}
</ul>
{% endif %}

This code would trigger the error mentioned above on the for loop.

Instead of using a variable I could refilter the original collection, but that doesn't seem optimal if it contains a lot of elements. I also thought about writing my own filter, wrapping the original one, but I'd live better if I didn't have to.

Is there anything better to do? Should this be considered a bug in Twig (in which case I'll open an issue in their repo)?

Note that https://github.com/dpolac/twig-lambda didn't exhibit this strange behavior but is not compatible with Twig 2.10.

Thanks


Solution

  • That was indeed a bug and it is now fixed