We learn about the join filter and how it's commonly used in a Craft CMS and Twig project.
The join
filter allows you to concatenate the elements of an array into a string, with an optional separator between each element.
If you work in PHP, you know this as the implode
function; it does the same thing: joins elements of an array into a string with an optional separator.
And, the join
filter will do the same. It’s most often used in conjunction with another operation, 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 running shoe brands. They are assigned to the array brands
.
If I just output this in Twig using the output tags ({{ }}
):
{{ brands }}
We get an array to string conversion error. This is because we’re asking Twig to output an array to the template as if it were a string. Which it isn’t, so we cannot.
To convert the array to a string, we use join
.
{{ brands | join }}
{# outputs "SalomonAltraBrooksHoka One OneMerrellLa Sportiva" #}
But that doesn’t look good, so the join
filter, just like the implode
function in PHP, let’s us specify the separator. We’ll use a comma.
{{ brands | join(', ') }}
{# outputs "Salomon, Altra, Brooks, Hoka One One, Merrell, La Sportiva" #}
And that looks nice! The join
filter gives us one more parameter we can use to make the string output even better: control over the final item.
I’m a fan of the Oxford comma, 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 tutorial and how I use the join filter in Craft CMS.
Refactoring with Twig Filters is made up of the following videos: