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

2

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

Intussusception answered 18/12, 2013 at 15:32 Comment(0)
I
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'))
Interloper answered 18/12, 2013 at 15:38 Comment(1)
sadly, Twig_Function_Method (as well as all Twig_Function_* classes) is deprecated. It will be removed in 2.0Intussusception
C
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}
Christiachristian answered 25/5, 2016 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.