Member-only story
Level Up Your Symfony Templates with Twig 3.15
From Arrow Functions to Safe Filtering — A Look at the Newest Twig Upgrades
Twig 3.15 has landed, and if you love crafting beautiful templates in Symfony, you’re in for a treat! This update brings some neat improvements that make your life easier.
Let’s break them down with practical examples and see how they can optimize your workflow.
Enhanced for
Loop Filtering
Ever needed to filter items right inside the for
loop? Now you can! Instead of filtering beforehand, just do it inline.
Old Way:
{% set filtered = items|filter(i => i.active) %}
{% for item in filtered %}
{{ item.name }}
{% endfor %}
New Way in Twig 3.15:
{% for item in items if item.active %}
{{ item.name }}
{% endfor %}
Cleaner, right? No need to pre-filter, just add the condition inside the loop!
Improved String Handling with filter
Twig 3.15 introduces a built-in filter
function for strings, making manipulations even smoother.
Example:
{{ ' Symfony is awesome! '|filter(s => s|trim|upper) }}