I used another solution to get data from a repository.
First, define the service:
## in bundle/Resources/config/services.yml
services:
YOUR_BUNDLE.twig.NAME_OF_THE_EXTENSION:
class: YOUR\BUNDLE\Twig\CLASSNAME
arguments:
- @service_container
tags:
- { name: twig.extension }
Then define the Twig extension class:
# YOUR_BUNDLE/Twig/CLASSNAME.php
<?php
namespace YOUR\BUNDLE\Twig;
class CLASSNAME extends \Twig_Extension
{
protected $container;
public function __construct($container)
{
$this->container = $container;
}
public function getGlobals()
{
return(array(
'unreadMessagesCount' => $this->container->get('doctrine')
->getManager()
->getRepository('YOUR_BUNDLE:UserRepository')
->getUnreadMessagesCount()
));
}
public function getName()
{
return 'NAME_OF_THE_EXTENSION';
}
}