5

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

SkaveRat
  • 1,889
  • 3
  • 16
  • 30

2 Answers2

12
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'))
deceze
  • 471,072
  • 76
  • 664
  • 811
  • 1
    sadly, `Twig_Function_Method` (as well as all `Twig_Function_*` classes) is deprecated. It will be removed in 2.0 – SkaveRat Dec 18 '13 at 16:39
4

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}
Turdaliev Nursultan
  • 2,350
  • 1
  • 18
  • 26