phptwigtemplating-engine

How to create a custom Twig function class, without using a static method?


I can create a Twig extension for my project like this

class Functions extends Twig_Extension{
    public function getName(){return 'foobar';}

    public function getFunctions() {
        return array(
            'loremipsum' => new \Twig_SimpleFunction('asset', 'Functions::loremipsum')
        );

    public static function loremipsum($foo) {
        return $foo;
    }
}

this works, but I want to use a constructor to inject some data that I need in some functions.

Simply using 'asset' in Twig_SimpleFunction will result in PHP trying to execute the functon loremipsum()


Solution

  • public function getFunctions() {
        return array(
            'foo' => new Twig_Function_Method($this, 'bar');
        );
    }
    
    public function bar($baz) {
        return $this->foo . $baz;
    }
    

    Look at all the different classes that extend Twig_Function for all the different ways to specify template functions.

    For the newer Twig_SimpleFunction, it seems you can pass any kind of callable as the second argument to the constructor:

    new Twig_SimpleFunction('foo', array($this, 'bar'))