in twig symfony ~ read.
Creating Twig Extensions in Symfony 3[EN]

Creating Twig Extensions in Symfony 3[EN]

Today we are going to see how to create extensions of Twig in Symfony3.
An extension of Twig is just a helper for our views, it will allow us to have a functionality that will allow to be used in any twig view of our Symfony project .
Just imgane that we want to format a number into money format:

{{ product.price|price }}

{# pass in the 3 optional arguments #}
{{ product.price|price(2, ',', '.') }}


To create extensions of Twig the first thing we have to do is to create a directory called Twig within our Bundle. And inside we create a class PHP, for example I will create the file GetUserExtension.php that will contain a class of the same name that will extend to the object Twig_Extension, it's a class that implements the following interface:

interface Twig_ExtensionInterface
{
    /**
     * Returns the token parser instances to add to the existing list.
     *
     * @return Twig_TokenParserInterface[]
     */
    public function getTokenParsers();

    /**
     * Returns the node visitor instances to add to the existing list.
     *
     * @return Twig_NodeVisitorInterface[]
     */
    public function getNodeVisitors();

    /**
     * Returns a list of filters to add to the existing list.
     *
     * @return Twig_Filter[]
     */
    public function getFilters();

    /**
     * Returns a list of tests to add to the existing list.
     *
     * @return Twig_Test[]
     */
    public function getTests();

    /**
     * Returns a list of functions to add to the existing list.
     *
     * @return Twig_Function[]
     */
    public function getFunctions();

    /**
     * Returns a list of operators to add to the existing list.
     *
     * @return array<array> First array of unary operators, second array of binary operators
     */
    public function getOperators();
}

<?php 
 
namespace AppBundle\Twig;
 
use Symfony\Bridge\Doctrine\RegistryInterface;
 
 
class GetUserExtension extends \Twig_Extension
{
 
   
    protected $doctrine;
 
    public function __construct(RegistryInterface $doctrine)
    {
        $this->doctrine = $doctrine;
    }
 
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('get_user', array($this, 'getUserFilter')),
        );
    }
 
  
    public function getUserFilter($user_id)
    {
        $user_repo = $this->doctrine->getRepository("BackendBundle:User");
 
        $user= $user_repo->findOneBy(array("id" => $user_id));
 
        if(!empty($user) && is_object($user)){
           $result = $user; 
        }else{
           $result = false;
        }
         
        return $result;
    }
 
    public function getName()
    {
        return 'get_user_extension';
    }
}

This extension, helper or filter will allow us to get the data of a given user id if it exists.
In order to use this extension in our views we have to add it as a service in our services.yml , in this case I pass doctrine to the service because we are also using it in the Twig extension class.

services:
    get_user.twig_extension:
        class: AppBundle\Twig\GetUserExtension
        public: false
        arguments:
            doctrine: "@doctrine"
        tags:
            - { name: twig.extension }

Now we can use the extension, in my case I save the user in a variable.

{% set user = myuser.id|get_user %}

Along with custom filters, you can also add custom functions and register global variables.

  1. Register a function:

    Functions can be registered in an extension via the getFunctions() method, here's an exampl:
class Project_Twig_Extension extends Twig_Extension
{
    public function getFunctions()
    {
        return array(
            new Twig_Function('lipsum', 'generate_lipsum'),
        );
    }

    // ...
}
  1. Global variables:
    Global variables can be registered in an extension via the getGlobals() method:
class Project_Twig_Extension extends Twig_Extension implements Twig_Extension_GlobalsInterface
{
    public function getGlobals()
    {
        return array(
            'text' => new Text(),
        );
    }

    // ...
}

And Voilà !