shapecode/twig-template-event-bundle

动态在 twig 模板中添加代码的可能性

5.0.0 2023-12-03 12:18 UTC

README

paypal

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

为您提供在 twig 模板中动态添加代码的可能性。

安装说明

首先您需要将 shapecode/twig-template-event-bundle 添加到 composer.json

composer require shapecode/twig-template-event-bundle

... 或者 ...

{
   "require": {
        "shapecode/twig-template-event-bundle": "~5.0"
    }
}

如果您不使用 Symfony Flex,您需要将 ShapecodeTwigTemplateEventBundle 添加到您的 bundles.php

<?php
// config/bundles.php

return [
    // ...
    Shapecode\Bundle\TwigTemplateEventBundle\ShapecodeTwigTemplateEventBundle::class => ['all' => true],
];

现在您可以在 twig 模板中设置事件

{{ event('test') }}

并通过事件监听器来监听它们

services:
    # twig events
    Shapecode\Bundle\TwigTemplateEventBundle\EventListener\TestTwigEventListener: ~
<?php

namespace Shapecode\Bundle\TwigTemplateEventBundle\EventListener;

use Shapecode\Bundle\TwigTemplateEventBundle\Event\Code\TwigEventString;
use Shapecode\Bundle\TwigTemplateEventBundle\Event\Code\TwigEventInclude;
use Shapecode\Bundle\TwigTemplateEventBundle\Event\TwigTemplateEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;

#[AsEventListener]
class TestTwigEventListener
{
    public function __invoke(TwigTemplateEvent $event): void
    {
        if ($event->getEventName() == 'foo') {
        
            // to add a string
            $event->addCode(
                new TwigEventString(
                    'hello {{ world }}', 
                    [
                        'world' => 'World'
                    ],
                    10 // default is 0. The higher the number the later the code will be executed. The lower the number the earlier the code will be executed.
                )
            );
        }
        
        if ($event->getEventName() == 'bar') {
        
            // to include a twig template
            $event->addCode(
                new TwigEventInclude(
                    '@App/Layout/Header/_search.html.twig', 
                    [
                        'world' => 'World'
                    ],
                )
            );
        }
    }
}