Twig 4.0 overhauls the `for` loop with several long-awaited improvements. The key change is that `loop.last` now works with any iterator (generators, Traversable objects) by reading one item ahead, not just arrays. New helpers include `loop.previous`/`loop.next` for accessing surrounding values, `loop.changed()` for grouping logic, and `loop.cycle()` for alternating CSS classes. The `if` condition on `for` tags returns after being removed in Twig 3.0. Recursive loops are now a first-class feature via the `loop()` function, replacing the verbose macro workaround. The upgrade path is smooth: templates running deprecation-free on Twig 3 render identically on Twig 4, with the only breaking change being clearer errors for non-countable iterators.
Table of contents
The Problem: A loop Variable Full of Holesloop.last Now Works with Any Iteratorloop.previous and loop.nextGrouping with loop.changed()Cycling with loop.cycle()The if Condition Is BackRecursive LoopsThe Upgrade Path90.8K Impressions4 Comments