There are several things going on here. This will be a general answer that can hopefully help you move forward. This example will use Sprout Active as a reference and you can see the code here for an example of a plugin that implements multiple, simple Twig Extensions.
Define your Twig Extension class and Namespace
In Craft 3, you can register a Twig Extension (or multiple Twig Extensions) in your Plugins init
. While the line to register the Twig Extension is straightforward, there are a lot of other details that matter in your file and I'll comment the code below to highlight why:
<?php
// In Craft 3, each class you create has a namespace. You need to
// make sure that this is referenced in any other classes that use this class
namespace barrelstrength\sproutactive;
// We're referencing the namespaces of other classes in this class too.
// We use the Craft Plugin class, to create our plugin
use craft\base\Plugin;
// You'll create this file next. We need to identify the namespace
// of the Twig Extension we'll be importing so Craft knows where it is
// when we reference `new TwigExtensions()` below
use barrelstrength\sproutactive\twig\TwigExtensions;
class SproutActive extends Plugin
{
public function init()
{
parent::init();
// Register the Twig Extensions file. We could name this anything
// and put this anywhere in our folder structure now. As long as
// we reference the namespace properly above, Craft will be able to
// find it. We can create multiple Twig Extensions within this
// TwigExtensions Class or create multiple files to manage our
// Twig Extensions and import those classes too.
Craft::$app->view->twig->addExtension(new TwigExtensions());
}
}
Twig 2 updated several things too
Once we get the extensions loaded, you can create extensions similar to before, however, Craft 3 uses Twig 2 which introduces several breaking changes on it's own. You can see some discussion of the Twig 2 front-end changes in the Craft docs but the docs don't discuss the API changes.
In Twig 2, Twig_SimpleFunction
replaces Twig_Function_Method
and Twig_Filter_Method
so you'll need to update any Craft 2 Twig Extensions code to use Twig_SimpleFunction
In the Sprout Active TwigExtensions
Class you can see how the class creates multiple Twig functions within the getFunctions
method.
public function getFunctions()
{
return [
new \Twig_SimpleFunction('active', [$this, 'getActive']),
new \Twig_SimpleFunction('activeClass', [$this, 'getActiveClass'], ['is_safe' => ['html']]),
new \Twig_SimpleFunction('segment', [$this, 'getSegment']),
new \Twig_SimpleFunction('segmentClass', [$this, 'getSegmentClass'], ['is_safe' => ['html']])
];
}
Test2TwigExtension
class exists and did you include it properly? Not sure what you mean with "I can't rename my filenames". When I create 2 separate twig extensions in two different files I can include them both withCraft::$app->view->registerTwigExtension(new ClassName());