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 the constructor to input some data that I need in some functions.

Just using 'asset'in Twig_SimpleFunctionwill cause PHP to try functonloremipsum()

+4
source share
2 answers
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 are extend Twig_Functionfor all the different ways you specify the functions of the template.

For the new, Twig_SimpleFunctionit seems that you can pass any callableas the second argument to the constructor:

new Twig_SimpleFunction('foo', array($this, 'bar'))
+9
source

1.23.1 :

class LogoExtension extends \Twig_Extension
{

    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('logo', array($this, 'logo'), array('is_safe' => array('html'))),
        );
    }

    public function logo()
    {
        return 'result';
    }


    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'logo';
    }
}

, , services.yml.

services:
    company.twig.extension.logo:
        class:  Acme\DemoBundle\Twig\Extension\LogoExtension
        tags:
            -   {   name:   twig.extension}
+3

All Articles