1

I have created an event to transform the entry data before rendering the page so that it's ready to render components in the template.

Event::on(View::class, View::EVENT_BEGIN_PAGE, [$this, 'transformSingleEntry']);

Here's an example of what the function looks like. I've cut out most of the code, but essentially at the end of the function I have a $transformed_entry variable that I want to add to the twig context.

public function transformSingleEntry() {
  $entry = Craft::$app->urlManager->getMatchedElement();
  // ... do stuff
  $transformed_entry = [
    'title' => 'test',
    'url' => 'test',
  ];
  // Add $transformed_entry to the page context
}

I cannot find anything in the Craft documentation to help here. Any ideas?

3

So the way Twig works is that it populates a Twig Environment with a context of global variables.

Then any time a template includes another template, the context is passed down to it.

So if you want something to be globally available you have to insert it into the Twig environment before Twig is used, for it to be truly globally available.

You can do that via a Twig extension that implements GlobalsInterface like this:

https://github.com/nystudio107/craft-seomatic/blob/v3/src/twigextensions/SeomaticTwigExtension.php#L36

So you might need to revise how you're doing it actually, and instead of using View::EVENT_BEGIN_PAGE you can just do whatever you need to do inside your Twig extension.

1
  • Thanks that example helped a lot – Callum May 26 '20 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.