Give you the possibility to add code in a twig template dynamically.
First you need to add shapecode/twig-template-event-bundle
to composer.json
:
{
"require": {
"shapecode/twig-template-event-bundle": "~3.0"
}
}
Please note that dev-master
points to the latest release. If you want to use the latest development version please use dev-develop
. Of course you can also use an explicit version number, e.g., 1.0.*
.
You have to add ShapecodeTwigTemplateEventBundle
to your AppKernel.php
:
<?php
// app/AppKernel.php
//...
class AppKernel extends Kernel
{
//...
public function registerBundles()
{
$bundles = array(
...
new Shapecode\Bundle\TwigTemplateEventBundle\ShapecodeTwigTemplateEventBundle(),
);
//...
return $bundles;
}
//...
}
Now you can set events in twig templates:
{{ event('test') }}
And listen to them with an event listener:
// services.yml
services:
# twig events
Shapecode\Bundle\TwigTemplateEventBundle\EventListener\TestTwigEventListener:
tags:
- { name: kernel.event_listener, event: shapecode.twig_template.event, method: onTemplateEvent }
<?php
namespace Shapecode\Bundle\TwigTemplateEventBundle\EventListener;
use Shapecode\Bundle\TwigTemplateEventBundle\Event\Code\TwigEventString;
use Shapecode\Bundle\TwigTemplateEventBundle\Event\TwigTemplateEvent;
class TestTwigEventListener
{
public function onTemplateEvent(TwigTemplateEvent $event): void
{
if ($event->getEventName() == 'test') {
$event->addCode(new TwigEventString('hello {{ world }}', array(
'world' => 'World'
)));
}
}
}