Extending Twig in Craft CMS

Setting Up a Craft Module to Extend Twig

The setup work in a Craft module to support a Twig extension.

This set­up will work for either a Craft mod­ule or plu­g­in. We’ll use a Craft mod­ule for this course since it’s the eas­i­est to get up and run­ning. If you don’t yet know how to code a Craft mod­ule, check out my course on it My First Craft Mod­ule.

There are two steps to get­ting a basic frame­work for a Twig exten­sion set up in Craft. First, we need to cre­ate the exten­sion class in our Craft plu­g­in or mod­ule. The sec­ond step is that to reg­is­ter the exten­sion with Craft vis the registerTwigExtension() method. This method tells Craft we have addi­tion­al Twig code to run when it spins up an instance of the application.

Let’s first set up our basic class file and then reg­is­ter our exten­sion in the main class file of our module.

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