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.

Instructor
Ryan Irelan
Level
Intermediate
Date Published
June 14, 2021
Ryan Irelan

I am the creator of CraftQuest, a web developer, and former software team manager. I spend most of my time improving CraftQuest with code and courses. When I'm not in front of the computer, I spend my time with my family, and running on the roads and trails of Austin, TX.