Skip to content

[TwigComponent] Allow specifying which template to render in component() Twig function #2818

Open
@FluffyDiscord

Description

@FluffyDiscord

I have the same Twig component form that I need to render differently in two places. I can always use EventListener for PreRenderEvent to adjust the template based on some variable, but it would be nice to have it built in. (I think this could be a built in thing, please tell me otherwise)

I propose this syntax/change:

{{ component('MyComponent', {
    '_template': 'some_other_template.html.twig'
}) }}

Where _template would be path to a different template, just like you can do using PreRenderEvent::setTemplate().

Basically adding this event listener by default:

<?php

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\UX\TwigComponent\Event\PreRenderEvent;

#[AsEventListener(PreRenderEvent::class)]
class ChangeComponentTemplateEventListener
{
    public function __invoke(PreRenderEvent $event): void
    {
        if (array_key_exists('_template', $event->getVariables())) {
            $event->setTemplate($event->getVariables()['_template']);
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions