In this refactoring video, we'll learn more about the map filter and how I am using it to refactor for-loops in CraftQuest's Twig templates.
The map filter in Twig allows us to alter each item in an array of data by applying a function and then return a new array in its changed form. The new array will have all of the items of the source array, but those items will be changed or mapped to a new form.
One thing you’ll notice about Twig is that many filters are Twig implementations of PHP functions. The map filter is yet another one.
Here’s a quick example:
{% set testResults = [43,32,30,50] %}
{{ testResults | map(result => result / 50 * 100 ~ "%") | join(', ') }}
We map over each number in the testResults array and calculate a grade percentage. In this video, we’ll learn more about the map filter, and how I used it to refactor some code on CraftQuest.

I am the creator of CraftQuest, a web developer, and former software team manager. I spend most of my time improving CraftQuest with code and courses. When I'm not in front of the computer, I spend my time with my family, and running on the roads and trails of Austin, TX.