Extending Twig in Craft CMS

Creating a Twig Global Variable

Learn how to add a Twig global variable to your Craft plugin or module via a Twig Extension.

In this video, we will learn how to cre­ate a Twig Glob­al Vari­able in Craft CMS. The goal is to pro­vide a vari­able ref­er­enc­ing data that we can use in any Twig tem­plate in our project. 

For this project, I want to build a vari­able that will always tell me if some­one is a pre­mi­um CraftQuest mem­ber or not. Since I do a lot of per­mis­sion work in the tem­plates repeat­ed­ly, I want to cen­tral­ize that as a Twig Glob­al Variable.

A Twig glob­al vari­able is like any oth­er vari­able in Twig except that it is avail­able in all tem­plates in your project. Com­mon glob­al vari­ables you’ve prob­a­bly used are currentUser, currentSite, or devMode.

We will build a sim­ple Twig glob­al vari­able with sta­t­ic data for this video and then cre­ate one for the CraftQuest project that gets its data from a ser­vice in a module.

Cre­at­ing a Sim­ple Twig Glob­al Variable

  1. Cre­ate a new direc­to­ry called twigextensions
  2. Cre­ate a class file for the Twig exten­sion. You can use just one for all of your Twig exten­sions, or use a ded­i­cat­ed class file just for your glob­als. We will start with a ded­i­cat­ed file and then show how to adapt to using an exist­ing Twig exten­sion class file.
<?php

namespace craftquest\twigextensions;

use Twig\Extension\AbstractExtension;  
use Twig\Extension\GlobalsInterface;

We import the AbstractExtension exten­sion class, which we’ll extend in our class def­i­n­i­tion. We also want to import the GlobalsInterface from Twig. This will define the [[PHP inter­face]] we’ll imple­ment in the class. This inter­face spec­i­fies how we must imple­ment our class for globals. 

Now to define the class:

namespace craftquest\twigextensions;

use Twig\Extension\AbstractExtension;  
use Twig\Extension\GlobalsInterface;

class CraftQuestTwigGlobals extends AbstractExtension implements GlobalsInterface
{

}

If you’re using Php­Storm as the IDE, you will see that the class defin­tion is under­lined in a red squigly line. This is because we haven’t ful­filled the require­ments of the inter­face we’re imple­ment­ing. This inter­face, the Glob­alsIn­ter­face, requires that we imple­ment a method called getGlobals();

Let’s add that now:

namespace craftquest\twigextensions;

use Twig\Extension\AbstractExtension;  
use Twig\Extension\GlobalsInterface;

class CraftQuestTwigGlobals extends AbstractExtension implements GlobalsInterface
{

	public function getGlobals(): array
	{
		
	}
}

Now we can begin to think about the glob­als that we want to return and the data we want to use to pop­u­late those globals. 

Remem­ber, a glob­al is some­thing that will be avail­able is every Twig tem­plate in our project. So, it needs to be some­thing glob­al­ly avail­able and not depen­dent on data the user just inputted, etc. 

Let’s just set it to some­thing sta­t­ic right now so we can test. 

The getGlobals() method returns an array so we need to struc­ture our glob­al data as such. Each glob­al vari­able will be its own item in the array. The key will of the array item will be the vari­able name when ref­er­enced in a Twig tem­plate, and the val­ue the value.

Let’s do some­thing sim­ple right now. 

namespace craftquest\twigextensions;

use Twig\Extension\AbstractExtension;  
use Twig\Extension\GlobalsInterface;

class CraftQuestTwigGlobals extends AbstractExtension implements GlobalsInterface
{

	public function getGlobals(): array
	{
		 return [

			'courseName' => 'Extending Twig in Craft CMS'
		
		];

	}
}

And then we return the array out of the method. This is a very sim­ple exam­ple and if we were doing this as part of a real project, we could just return the array direct­ly rather than assign­ing it to a vari­able we don’t use.

Before we can do this, we need to load our new Twig exten­sion in the mod­ule class file and then rebuild the Com­pos­er aut­load files so it picks up the new class we created.

$ composer dump-autoload

In the mod­ule class file – in my exam­ple this is the CQControlPanel.php class file – we already have the basics in place from our ear­li­er work in the course. What we need to do now is add our new Twig exten­sion class file to the array inside the pri­vate _registerTwigExtensions method and then it’ll be loaded in via registerTwigExtension() as it loops over the array of exten­sions to register. 

The method is called up in the init() when the mod­ule is first loaded.

    private function _registerTwigExtensions()
    {
        $extensions = [
            PlantifyExtension::class,
            CraftquestTwigExtension::class,
        ];

        foreach ($extensions as $extension) {
            Craft::$app->view->registerTwigExtension(new $extension);
        }
    }

With our basic class ready, let’s Let’s test this by adding the new glob­al vari­able to the index.twig tem­plate via {{ courseName }}.

{{ courseName }}

And, it should work!

Of course, this isn’t a very prac­it­cal use of a glob­al but we have the basics set up and then only we need to do now is decide what kind of vari­ables we need to pop­u­late. Con­tin­ue watch­ing the rest of the video as I cre­ate a Twig glob­al vari­able for the CraftQuest site and pop­u­late it with data from a mod­ule service.

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