Register Twig functions that are in another class

537 views Asked by At

If I do:

protected function registerTwigFunctions() {
    return [
        'mytwigfunction' => 'myTwigFunction',
    ];
}

then everything works, provided that my function is in the same class.

But I'm struggling in an attempt to register a Twig function that is in another class.

If I do:

protected function registerTwigFunctions() {
    return [
        'mytwigfunction' => [[anotherClass::class, 'myTwigFunction']],
    ];
}

then I get Unable to load the "My\Name\Space\AnotherClass" runtime in "record.twig" at line 1., even though it picks up its namespace correctly, and of course I have it imported.

I also played with the syntax, but it would throw different kinds of errors. And I believe that this syntax is correct.

I'm asking this question in the context of Bolt CMS just in case if there's something different from standard Symfony regarding registering Twig functions, but I doubt it.

1

There are 1 answers

0
Michał Tomczuk On

The issue is that probably your myFunction method is not static. Imagine a class:

class Element
{
    public static function sayHi()
    {
        return "Hi!";
    }

    public function sayHello()
    {
        return "Hello!";
    }
}

In order to use this in Twig function you register them like so:

public function getFunctions()
    {
        $element = new Element();

        return [
            new TwigFunction('test_function_static', [Element::class, 'sayHi']),
            new TwigFunction('test_function_dynamic_on_object', [$element, 'sayHello']),
        ];
    }

So basically the callable has to adhere to the rules, meaning that you can call a non-static function only on an object (instance) of certain class, not on the class itself.

If you would add

    ...
    new TwigFunction('test_function_dynamic_on_class', [Element::class, 'sayHello']),
    ...

you would see the error you are having.