Craft 3 Documentation

Extending Twig

Craft provides two ways for plugins to extend its Twig templating environment.

Extend the Global craft Variable #

The global craft template variable is an instance of craft\web\twig\variables\CraftVariable. When a template references craft.entries or craft.entries(), it’s calling CraftVariable::entries() behind the scenes, for example.

The CraftVariable instance can be extended by plugins with behaviors and services. Choosing the right approach depends on what you’re trying to add to it.

You can attach your behavior or service to the CraftVariable instance by registering an EVENT_INIT event handler from your plugin’s init() method:

use craft\web\twig\variables\CraftVariable;
use yii\base\Event;

public function init()
{
    parent::init();

    Event::on(CraftVariable::class, CraftVariable::EVENT_INIT, function(Event $e) {
        /** @var CraftVariable $variable */
        $variable = $e->sender;

        // Attach a behavior:
        $variable->attachBehaviors([
            MyBehavior::class,
        ]);

        // Attach a service:
        $variable->set('serviceId', MyService::class);
    });
}

Register a Twig Extension #

If you want to add new global variables, functions, filters, tags, operators, or tests to Twig, you can do that by creating a custom Twig extension.

Twig extensions can be registered for Craft’s Twig environment by calling craft\web\View::registerTwigExtension() from your plugin’s init() method:

public function init()
{
    parent::init();

    if (Craft::$app->request->getIsSiteRequest()) {
        // Add in our Twig extension
        $extension = new MyTwigExtension();
        Craft::$app->view->registerTwigExtension($extension);
    }
}