Skip to content

Commit 4262565

Browse files
committed
minor #316 clarifying that PreRenderEvent is a true event (weaverryan)
This PR was merged into the 2.x branch. Discussion ---------- clarifying that PreRenderEvent is a true event | Q | A | ------------- | --- | Bug fix? | no | New feature? | no | Tickets | fixes question from Slac | License | MIT A user in Slack wasn't sure if `PreRenderEvent` was meant to be leveraged inside an event subscriber or if it was more like a "hook" that went into the component class. So, I expanded the example. Cheers! Commits ------- c3e277f clarifying that PreRenderEvent is a true event
2 parents b0500d9 + c3e277f commit 4262565

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

src/TwigComponent/src/Resources/doc/index.rst

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -611,21 +611,30 @@ PreRenderEvent
611611
Subscribing to the ``PreRenderEvent`` gives the ability to modify
612612
the twig template and twig variables before components are rendered::
613613

614+
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
614615
use Symfony\UX\TwigComponent\EventListener\PreRenderEvent;
615616

616-
public function preRenderListener(PreRenderEvent $event): void
617+
class HookIntoTwigPreRenderSubscriber implements EventSubscriberInterface
617618
{
618-
$event->getComponent(); // the component object
619-
$event->getTemplate(); // the twig template name that will be rendered
620-
$event->getVariables(); // the variables that will be available in the template
619+
public function onPreRender(PreRenderEvent $event): void
620+
{
621+
$event->getComponent(); // the component object
622+
$event->getTemplate(); // the twig template name that will be rendered
623+
$event->getVariables(); // the variables that will be available in the template
624+
625+
$event->setTemplate('some_other_template.html.twig'); // change the template used
621626

622-
$event->setTemplate('some_other_template.html.twig'); // change the template used
627+
// manipulate the variables:
628+
$variables = $event->getVariables();
629+
$variables['custom'] = 'value';
623630

624-
// manipulate the variables:
625-
$variables = $event->getVariables();
626-
$variables['custom'] = 'value';
631+
$event->setVariables($variables); // {{ custom }} will be available in your template
632+
}
627633

628-
$event->setVariables($variables); // {{ custom }} will be available in your template
634+
public static function getSubscribedEvents(): array
635+
{
636+
return [PreRenderEvent::class => 'onPreRender'];
637+
}
629638
}
630639

631640
Embedded Components

0 commit comments

Comments
 (0)