-
Notifications
You must be signed in to change notification settings - Fork 627
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
EVENT_AFTER_CREATE_TWIG #11774
EVENT_AFTER_CREATE_TWIG #11774
Conversation
[ci skip]
So this is great except for one small thing... this sequence of code: // Set our timezone
/** @var CoreExtension $core */
$core = $twig->getExtension(CoreExtension::class);
$core->setTimezone(Craft::$app->getTimeZone());
// Fire an 'afterCreateTwig' event
if ($this->hasEventHandlers(self::EVENT_AFTER_CREATE_TWIG)) {
$this->trigger(self::EVENT_AFTER_CREATE_TWIG, new CreateTwigEvent([
'templateMode' => $this->_templateMode ?? self::TEMPLATE_MODE_SITE,
'twig' => $twig,
]));
} ...doesn't allow an event listener to add extensions to Twig, because the call to You might want to change the event sequence to be: // Fire an 'afterCreateTwig' event
if ($this->hasEventHandlers(self::EVENT_AFTER_CREATE_TWIG)) {
$this->trigger(self::EVENT_AFTER_CREATE_TWIG, new CreateTwigEvent([
'templateMode' => $this->_templateMode ?? self::TEMPLATE_MODE_SITE,
'twig' => $twig,
]));
// Set our timezone
/** @var CoreExtension $core */
$core = $twig->getExtension(CoreExtension::class);
$core->setTimezone(Craft::$app->getTimeZone());
} |
To register Twig extensions, you should be using |
Right, but even if we added the extension that way via the Twig lazily initializes itself if Without that, there really isn't much that can be done in that event callback in terms of modifying the Twig environment before Craft uses it. |
Okay I looked at the code for So for this specific thing, yes, that's a workable solution. There are other ways you might want to modify the Twig environment that it still might be useful to move the event to before Twig gets initialized, IMO, but up to you. |
…_CREATE_TWIG` to hook Closure in, so it will work with any Craft-created Twig environment (not just when rendering page templates) ([#11774](craftcms/cms#11774))
Adds an
EVENT_AFTER_CREATE_TWIG
event tocraft\web\View::createTwig()
, which can be called by plugins if they need to fire at the moment a Twig environment is created.Since Craft creates separate Twig environments for control panel and site templates, the event class has a
templateMode
property which will either be set tocp
orsite
depending on the active template mode, in case it’s relevant to the handler.