Skip to content

Render Twig component from Twig extension #4537

@michalschroeder

Description

@michalschroeder

Hi and happy new year :)

I'm trying to use an anonymous Twig component in my Twig extension, something like this:

templates/components/Test.html.twig

<div {{ attributes }}>
    Test
</div>

My Twig extension class

final class TestExtension extends AbstractExtension
{
    /**
     * @return list<TwigFilter>
     */
    #[\Override]
    public function getFilters(): array
    {
        return [
            new TwigFilter(
                'test',
                $this->test(...),
                [
                    'is_safe' => ['html'],
                ],
            ),
        ];
    }

    public function test(): string
    {
        return <<<'HTML'
                <twig:Test>TEST</twig:Test>
            HTML;
    }
}

The effect is that it renders this as a simple string <twig:Test>TEST</twig:Test> in the HTML output, so it's not detecting that it should be rendered as a Twig component. Is that expected behavior? Or I'm using it wrongly?
image

I came up with two different solutions to make it work.

1. Use Twig Environment like this:

final class TestExtension extends AbstractExtension
{
    ...

    public function test(Environment $twig): string
    {
        $template = <<<'HTML'
               <twig:Test>TEST</twig:Test>
            HTML;

        return $twig->createTemplate($template)->render();
    }
}

2. Use ComponentRendererInterface like this

final class TestExtension extends AbstractExtension
{
    ...

    public function test(): string
    {
        return $this->componentRenderer->createAndRender('Test');
    }
}

But TBH I'm not convinced if that's the correct solution. From my perspective both have downsides and I'm curious what's the recommended way to make it work?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions