Refactoring with Twig Filters

Refactoring with the join Filter in Twig

We learn about the join filter and how it's commonly used in a Craft CMS and Twig project.

The join fil­ter allows you to con­cate­nate the ele­ments of an array into a string, with an option­al sep­a­ra­tor between each element.

If you work in PHP, you know this as the implode func­tion; it does the same thing: joins ele­ments of an array into a string with an option­al separator.

And, the join fil­ter will do the same. It’s most often used in con­junc­tion with anoth­er oper­a­tion, like a map, but let’s look at the basic usage of it and then watch the video on how I use it in CraftQuest.

{% set brands = ['Salomon', 'Altra', 'Brooks', 'Hoka One One', 'Merrell', 'La Sportiva'] %}

Here I have an array of trail run­ning shoe brands. They are assigned to the array brands.

If I just out­put this in Twig using the out­put tags ({{ }}):

{{ brands }}

We get an array to string con­ver­sion error. This is because we’re ask­ing Twig to out­put an array to the tem­plate as if it were a string. Which it isn’t, so we cannot.

To con­vert the array to a string, we use join.

{{ brands | join }}
{# outputs "SalomonAltraBrooksHoka One OneMerrellLa Sportiva" #}

But that doesn’t look good, so the join fil­ter, just like the implode func­tion in PHP, let’s us spec­i­fy the sep­a­ra­tor. We’ll use a comma.

{{ brands | join(', ') }}
{# outputs "Salomon, Altra, Brooks, Hoka One One, Merrell, La Sportiva" #}

And that looks nice! The join fil­ter gives us one more para­me­ter we can use to make the string out­put even bet­ter: con­trol over the final item. 

I’m a fan of the Oxford com­ma, so let’s add that at the end of the string of brands.

{{ brands | join(', ', ' and ') }}
{# outputs "Salomon, Altra, Brooks, Hoka One One, Merrell, and La Sportiva" #}

Ah, much nicer!

Watch the video to see the rest of the tuto­r­i­al and how I use the join fil­ter in Craft CMS.

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