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()

有帮助吗?

解决方案

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'))

其他提示

Update from twig version 1.23.1 and up it's as follows:

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';
    }
}

And of course, you add this extension class as a twig extension on services.yml config file.

services:
    company.twig.extension.logo:
        class:  Acme\DemoBundle\Twig\Extension\LogoExtension
        tags:
            -   {   name:   twig.extension}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top