How to display global variable in twig?

1.3k Views Asked by At

Controller

$count_em =  $this->getDoctrine()->getRepository('AppBundle:St_Jude_Email');
    $count_dql = $count_em->createQueryBuilder('c')
            ->select('count(c.flag)')
            ->where('c.flag = 0');
    $flag_count = $count_dql->getQuery();
    $count = $flag_count->getSingleScalarResult();

    return $count;

Config.yml

 Twig:
  globals:  
    count: '@AppBundle\Controller\countMail'

How to display count which is global in twig?? I'm sorry, I'm new to the symfony and have no idea how to display 'count' in twig. I tried doing {{ count }} , but got error 'An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class AppBundle\Controller\countMail could not be converted to string").'

3

There are 3 best solutions below

0
On

You should create a service e.g. MailService, which holds e.g. a countAllMail() method. In this method you can do your DB stuff. After that you can do the following:

config.yml

twig:
    globals:
        my_global_mail_service: '@AppBundle\Service\MailService'

And in your twig template you can use your service like this

{{ my_global_mail_service.countAllMail() }}
1
On

If you need to return it to Template - return it as an array.

return ['count' => $count];

In other cases, if you need use globally, you need to use twig extension, look this documentation.

0
On

@AppBundle\Controller\countMail - that's a service reference. In your case you need to create a symfony service - https://symfony.com/doc/current/service_container.html Then reference that service as a global twig var. Then in your template you an reference any public method from the service e.g {{ count.methodThat ReturnsSomeValue }}

with this approach you don't need to pass anything to twig renderer in each controller action