Skip to content

Use the same code as both a Function and a Filter #4332

Answered by stof
pgorod asked this question in Q&A
Discussion options

You must be logged in to vote

A Twig extension can totally reuse the same PHP callable to implement a Twig filter and a Twig function:

<?php

// use statements omitted for brevity

class MyExtension extends AbstractExtension
{
    public function getFilters(): array
    {
        return [new TwigFilter('myExt', $this->myExt(...)];
    }

    public function getFunctions(): array
    {
        return [new TwigFunction('myExt', $this->myExt(...)];
    }

    public function myExt($arg1, $arg2)
    {
        // TODO implement the logic
    }
}

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@pgorod
Comment options

Answer selected by pgorod
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants