shapecode/twig-template-event-bundle

Possibility to add code in a twig template dynamically

4.0.1 2020-09-10 07:16 UTC

This package is auto-updated.

Last update: 2021-10-10 09:44:49 UTC


README

paypal

PHP Version Latest Stable Version Latest Unstable Version Total Downloads Monthly Downloads Daily Downloads License

Give you the possibility to add code in a twig template dynamically.

Install instructions

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'
            )));
        }
    }
}