Skip to content

[RFC][TwigBundle] Register custom functions & filters using an attribute #50016

@artyuum

Description

@artyuum

Description

Currently, in order to create a custom twig function/filter, we need create a class that extends the AbstractExtension, that looks like this:

class TwigExtension extends AbstractExtension
{
    public function getFilters(): array
    {
        return [
            new TwigFilter('my_custom_filter', 'myCustomFilter'),
        ];
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('my_custom_function', 'myCustomFunction'),
        ];
    }

    public function myCustomFilter(): string
    {
        // code here
    }

    public function myCustomFunction(): string
    {
        // code here
    }
}

Example

I've always thought that the DX regarding twig extension could be better when working with Symfony. Today, I imagined the following:

class TwigExtension extends AbstractExtension
{
    #[TwigFilter('my_custom_filter')]
    public function myCustomFilter(): string
    {
        // code here
    }

    #[TwigFunction('my_custom_function')]
    public function myCustomFunction(): string
    {
        // code here
    }
}

If we don't want to modify or conflict with the existing TwigFunction / TwigFilter classes, we could name them like this and store them in the twig bridge I think?

  • #[AsTwigFilter]
  • #[AsTwigFunction]

What do you think?

(If the feedbacks are positive, I'll open a PR.) Hum, this seems more difficult than I initially thought.

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