Extending Twig in Craft CMS

Extending Twig with a Function

Now we set our sights on creating a Twig function. This is quick and easy because all of the supporting code is already there.

With our Twig fil­ter done, let’s focus on a func­tion. The dif­fer­ence between a fil­ter and func­tion is that a fil­ter is about manip­u­lat­ing data passed into the fil­ter and then return­ing it. A func­tion, on the oth­er hand, is for when you want to gen­er­ate some­thing, like content. 

But a func­tion can also be help­ful when you need to pass in some argu­ments that will be used to manip­u­late or con­trol out­put of the data.

In our case, we want to build two func­tions (one this video and one in the next). One will out­put a list of plant-based ingre­di­ents. This is our con­tent gen­er­a­tion exam­ple. The oth­er will trans­form any text passed into it along with the replace­ment val­ues passed in as an argument. 

We already have our Twig exten­sion class cre­at­ed and ini­tial­ized in the mod­ule class file, so we can focus sole­ly on cre­at­ing a cou­ple of functions.

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