2
votes

Here is the Symfony Guide to writing Twig Extensions: http://symfony.com/doc/current/cookbook/templating/twig_extension.html

Note it says to provide:

// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;

class AppExtension extends \Twig_Extension
{
    public function getName()
    {
        return 'app_extension';
    }
}

Here is the Twig API: https://github.com/twigphp/Twig/blob/1.x/lib/Twig/Extension.php

There is no getName function() there.

So why do we have to provide one? What purpose does it serve?

3

3 Answers

2
votes

Look at Twig_ExtensionInterface, which Twig_Extension implements, getName() need to be implemented in your custom twig extension according to the interface.

According to twig documentation by folks at sensiolabs (link here):

To keep your extension class clean and lean, it can inherit from the built-in Twig_Extension class instead of implementing the whole interface. That way, you just need to implement the getName() method as the Twig_Extension provides empty implementations for all other methods.

The getName() method must return a unique identifier for your extension.

1
votes

Method getName() is defined in Twig_ExtensionInterface implemented by Twig_Extension.

Source here: https://github.com/twigphp/Twig/blob/1.x/lib/Twig/ExtensionInterface.php

Its nice way to ensure every Extension will have name.

0
votes

Like @DarkBee mentioned in his comment, the getName() method of class Twig_ExtensionInterface has been removed in version 2.0 of Twig.

From Twig 1.x API we can see that that the method has been deprecated since version 1.26 and removed in version 2.0. It can be seen also in the changelog:

1.26.0 (2016-10-02)

  • ...
  • deprecated Twig_ExtensionInterface::getName()

In addition, looking e.g. at the getExtension($name) method in Environment.php of Twig version 1.25.0, we can see that the method is used to get an extension by its name, whereas in version 1.26.0 and version 2.4.4, the method is used to get an extension by its class name.

So,

  • If you use Twig version 1.25 or earlier, you need to implement the getName() method.
  • If you use Twig version 1.26.0 (released 2nd Oct 2016) or later, or version 2.x, you shouldn't implement the getName() method. (Well, you can, but it's not used by Twig.)