Extending Twig in Craft CMS

Extending Twig with a Filter

We code a filter that manipulates a string of text passed in via and returns it to the Twig template.

With the basic set­up done, let’s code our fil­ter. But before we do that let’s define what a Twig fil­ter is and when to use it.

A Twig fil­ter is a way of manip­u­lat­ing or trans­form­ing data passed into the fil­ter and then out­putted. A com­mon exam­ple, and an actu­al Twig fil­ter, is to upper­case every let­ter in the passed in text.

{{ "craftquest" | upper }}

That would result in CRAFTQUEST as the out­put because we pass the string into the upper fil­ter. This fil­ter is a default fil­ter that is part of the core Twig library. 

Before you build your own fil­ter, you should check that it doesn’t already exist in the core Twig fil­ters or in fil­ters pro­vid­ed by Craft CMS.

But, the main thing to remem­ber, is that we want to use a fil­ter when we need to trans­form the passed val­ue to some­thing else. If we need to also pass in addi­tion­al para­me­ters, then the Twig fil­ter isn’t for us. 

For our plantify fil­ter, we are going to pass in the text and then scrub it of meat ref­er­ences and replace it with a plant-based ref­er­ence. We aren’t going to get fan­cy with our find and replace or the dic­tio­nary of terms we use to replace.

The goal here is to learn the frame­work of build­ing a Twig fil­ter, not the details of a spe­cif­ic imple­men­ta­tion. We could make this as sim­ple or com­pli­cat­ed as want. It could be just call­ing a sin­gle native PHP func­tion and then return­ing that or we could call our cus­tom ser­vices, con­nect to a third-par­ty web ser­vice to process data, etc. It can do what­ev­er we want. But for right now we will keep it simple.

Extending Twig in Craft CMS is made up of the following videos: