Creating an extension for twig is very useful and important: access a specific variable anywhere, increase app efficiency by setting up autonomous block etc.
Here are my sources:
Declare your service into service.yml (curious, isn’t it ? :). Don’t forget to enable it in DependencyInjection\YourBundleExtension by uncommenting $loader->load(‘services.yml’) and then:
services:
breaz.twig.my_name:
class: Breaz\CoreBundle\Twig\NameitExtension
arguments: [@doctrine,@security.context]
tags:
- { name: twig.extension }
Then the file:
namespace Acme\XXXBundle\Twig;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\SecurityContext;
class NameitExtension extends \Twig_Extension {
private $em;
private $user;
public function __construct(Registry $doctrine, $context) {
if (!is_object($context->getToken())) {
return;
}
$this->user = $context->getToken()->getUser();
$this->em = $doctrine->getManager();
}
public function getFunctions()
{
return array(
// Add any function you need and declare them in your object
‘nb_favorite’ => new \Twig_Function_Method($this, ‘nbFavorite’)
);
}
public function nbFavorite()
{
// Put your code here
}
public function getName()
{
return ‘NameitExtension’;
}
}
This file allow you to call {{ nb_favorite() }} in any twig template. It will return the value you defined above.