Search code examples
symfonysymfony-2.6

Symfony2 - get the return of controller in twig template


my twig template "backoffice.html.twig" is on Egov/AdminBundle and extends baseBO.html.twig

it contains this block

{% block notificationD %}  {% endblock %}

and in Egov/PosteBundle/Controller/CcpAdminController.php i have this function

public function getDemandeEnCourAction()
{
    $repo = $this   ->getDoctrine()
        ->getManager()
        ->getRepository('EgovCoreBundle:DemandeCCP');

    $qb = $repo->createQueryBuilder('d');
    $qb->select('COUNT(d)');
    $qb->where('d.statut  = :statut');
    $qb->setParameter('statut', 'en cour');
    $count = $qb->getQuery()->getSingleScalarResult();
    return $this->render('@EgovAdmin/Default/backoffice.html.twig', array(
        'count' => (int) $count,
    ));
}

So when i do that

{% block notificationD %} {{ count }} {% endblock %}

i have this exception :

Variable "count" does not exist in @EgovAdmin/Default/backoffice.html.twig 

and if i use render controller like this nothing to change :

render(controller("EgovPosteBundle:CcpAdmin:getDemandeEnCour"))

Solution

  • The poster indicated that a twig extension was too much work but here is an example anyways:

    class MyExtension extends \Twig_Extension
    {
      private $em;
      public function __construct($em) 
      {
        $this->em = $em;
      }
      public function getFunctions()
      {
        return [            
          new \Twig_SimpleFunction('demande_count',[$this, 'getDemandeCount']),
        ];
      }
      public function getDemandeCount()
      {
        $repo = $this->em->getRepository('EgovCoreBundle:DemandeCCP');
    
        $qb = $repo->createQueryBuilder('d');
        $qb->select('COUNT(d)');
        $qb->where('d.statut  = :statut');
        $qb->setParameter('statut', 'en cour');
        return $qb->getQuery()->getSingleScalarResult();
      }
    

    Define as a service:

    services:
      demande_count:
        class: MyExtension
        arguments: ['@doctrine.orm.default_entity_manager']
        tags: [{ name: twig.extension }]
    

    Then use it in whatever template needs it with:

    {{ demande_count() }}
    

    No fuss. No muss;