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.
Follow along with the full transcript
Search every word, click any line to jump to that moment, and read along as you watch — a CraftQuest Premium feature.
Sign up for Premium