We code a filter that manipulates a string of text passed in via and returns it to the Twig template.
With the basic setup done, let’s code our filter. But before we do that let’s define what a Twig filter is and when to use it.
A Twig filter is a way of manipulating or transforming data passed into the filter and then outputted. A common example, and an actual Twig filter, is to uppercase every letter in the passed in text.
{{ "craftquest" | upper }}
That would result in CRAFTQUEST
as the output because we pass the string into the upper
filter. This filter is a default filter that is part of the core Twig library.
Before you build your own filter, you should check that it doesn’t already exist in the core Twig filters or in filters provided by Craft CMS.
But, the main thing to remember, is that we want to use a filter when we need to transform the passed value to something else. If we need to also pass in additional parameters, then the Twig filter isn’t for us.
For our plantify
filter, we are going to pass in the text and then scrub it of meat references and replace it with a plant-based reference. We aren’t going to get fancy with our find and replace or the dictionary of terms we use to replace.
The goal here is to learn the framework of building a Twig filter, not the details of a specific implementation. We could make this as simple or complicated as want. It could be just calling a single native PHP function and then returning that or we could call our custom services, connect to a third-party web service to process data, etc. It can do whatever we want. But for right now we will keep it simple.
Extending Twig in Craft CMS is made up of the following videos: