Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Twig Template Event Bundle Laravel Package

shapecode/twig-template-event-bundle

A Symfony bundle that adds event dispatching around Twig template rendering, letting services hook into template resolution and output without modifying individual templates.

View on GitHub
Deep Wiki
Context7

Getting Started

Install the bundle via Composer:

composer require shapecode/twig-template-event-bundle

Register it in config/bundles.php (Symfony Flex usually does this automatically):

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

Look first at the bundle's src/ directory — specifically the Event/ (or Events/) namespace for the event constants/event classes, and the EventListener/ subscriber that ships with the bundle. That subscriber is what hooks into Twig rendering; reading it is the fastest way to understand exactly when the events fire and what data the event object exposes (getTemplate(), getContext(), etc.).

First use case: subscribe to the pre/post template render events so you can inspect every template that gets rendered. Create a listener:

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Shapecode\TwigTemplateEventBundle\Event\TemplateEvent;
use Shapecode\TwigTemplateEventBundle\Event\TemplateEvents;

#[AsEventListener(event: TemplateEvents::PRE_RENDER)]
final class TemplateRenderLogger
{
    public function __invoke(TemplateEvent $event): void
    {
        error_log('Rendering: '.$event->getTemplate());
    }
}

Once you've confirmed events fire (via log output or a Symfony profiler event panel), you have a working baseline and can layer behaviour on top.

Implementation Patterns

Analytics / observability. Listen for both pre- and post-render events to time how long each template takes. Pair with a Stopwatch or Microtime map keyed by template name so you can report slow-rendered templates — useful in a large app where cache misses silently become a page-speed issue.

Global context injection. Use the pre-render event to add shared variables that don't belong in a Twig extension — for example, flagging whether the current request is a sub-request, injecting app.request.attributes values, or setting a request-scoped csrf token. Because you have the template name, you can scope injections to specific templates only:

if ($event->getTemplate() === 'emails/base.html.twig') {
    $event->getContext()['unsubscribeUrl'] = $this->unsubscribeUrl;
}

Security / auditing. Post-render is a natural place to audit "which templates exposed data for this request" — useful for compliance or for debugging which template is leaking a value into a page.

Debugging pipeline. Build a small dev-only listener that collects rendered templates into a request attribute and dumps them in the toolbar. This is a cheap way to answer "what templates did this page actually render?" without re-running with Twig's debug mode.

Integration tips. Keep listeners lightweight — they run on every template render (including partials, embeds, and macros), so a heavy DB call inside a listener will multiply across the whole page. Prefer injecting services lazily and short-circuiting early with a return when the current template name isn't one you care about. Prefer an #[AsEventListener]-attributed class with a TemplateEvents::PRE_RENDER constant so you don't have to guess the string event name.

Gotchas and Tips

It fires on every template, including includes. Most people expect one event per request — in practice you'll get one per template (including {% include %}, {% embed %}, macros, and form-theme renders). If you only care about the top-level template, filter using the context's app.request attributes or capture the first render per request.

Context is mutable but fragile. The event object exposes the render context; modifying it works only if the bundle passes context by reference (check the shipped event class — this is version-dependent). When in doubt, don't mutate; add variables through a Twig extension or Twig\Environment::addGlobal at kernel boot instead.

Bundle is small / low activity (10 stars). Expect limited documentation and no guarantee of forward compatibility across Symfony major versions. Treat the event names/class names as an internal contract: add a thin wrapper (your own event class) if you plan to depend on it across multiple projects, so upgrading the bundle doesn't ripple through every listener.

No performance safety net. There's no caching mechanism built in; every render dispatches listeners. Avoid enabling verbose listeners in prod unless you've benchmarked. Gate debug listeners with %kernel.debug%.

Twig caching doesn't skip the events. Dispatched at runtime during render(), events still fire when the compiled template is served from the Twig cache. That's usually what you want (context-dependent logic), but means you cannot rely on them to detect cache misses.

Debugging checklist. If listeners aren't firing: (1) confirm the bundle is registered, (2) php bin/console debug:event-dispatcher and search for the template event names, (3) verify you're on the event constant the bundle actually dispatches — the vendor class is authoritative, not the README, (4) check that you aren't rendering through a different Twig environment (e.g. a standalone Twig\Environment created outside Symfony).

Extension points. If the bundle doesn't already ship a way to inspect the compiled TemplateWrapper, the practical extension path is to wrap the bundle's listener with your own higher-priority subscriber (priority: 10) and decorate the event data before anything downstream consumes it. This keeps you decoupled from the bundle internals while still using its dispatch points.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
uni-method/symfony-lib
tacticmedia/scim-server-bundle
neika-ai/symfony-bundle
mattleads/agent-publishing-bundle
glavweb/framework-bundle
glavweb/extra-bundle
glavweb/api-bundle
glavweb/admin-bundle
adachsoft/api-version-bundle
elsayed85/laravel-api-exceptions
ouhssini/laravel-demo-mode
daworks/ncloud-outbound-mailer-driver
gp247/cms
ignibyte/aic-gates
nexa-merchant/blog
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
cgv/localized-resource