Refactoring with Twig Filters

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.

Refactoring with Twig Filters is made up of the following videos: