2026 Community Survey results are here! See how the Craft CMS community works. results are live!

Refactoring with the map Filter in Twig

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 fil­ter in Twig allows us to alter each item in an array of data by apply­ing a func­tion 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 fil­ters are Twig imple­men­ta­tions of PHP func­tions. The map fil­ter is yet anoth­er one. 

Here’s a quick example:

{% set testResults = [43,32,30,50] %}

{{ testResults | map(result => result / 50 * 100 ~ "%") |  join(', ') }}

We map over each num­ber in the testResults array and cal­cu­late a grade per­cent­age. In this video, we’ll learn more about the map fil­ter, and how I used it to refac­tor some code on CraftQuest.

Craft Version
Craft 4
Topic
Instructor
Ryan Irelan
Level
Intermediate
Date Published
September 29, 2023
Ryan Irelan

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.