Search code examples
symfonydoctrine-ormtwigtwig-extension

How to have a global variable coming from db in symfony template?


How can I have a global variable in symfony template? I did read this but I prefer to fetch parameter from database, I think this service will be loaded on startup before it can fetch anything from db. Is it possible to do a trick to do so?


Solution

  • EDIT: Update in 2019 with Symfony 3.4+ syntax.

    Create a Twig extension where you inject the Entity Manager:

    Fuz/AppBundle/Twig/Extension/DatabaseGlobalsExtension.php

    <?php
    
    namespace Fuz\AppBundle\Twig\Extension;
    
    use Doctrine\ORM\EntityManager;
    use Twig\Extension\AbstractExtension;
    use Twig\Extension\GlobalsInterface;
    
    class DatabaseGlobalsExtension extends AbstractExtension implements GlobalsInterface
    {
    
       protected $em;
    
       public function __construct(EntityManager $em)
       {
          $this->em = $em;
       }
    
       public function getGlobals()
       {
          return [
              'myVariable' => $this->em->getRepository(FuzAppBundle\Entity::class)->getSomeData(),
          ];
       }
    }
    

    Register your extension in your Fuz/AppBundle/Resources/config/services.yml:

    services:
        _defaults:
            autowire: true
            autoconfigure: true 
    
        Fuz\AppBundle\Twig\Extension\DatabaseGlobalsExtension: ~
    

    Now you can do the requests you want using the entity manager.

    Don't forget to replace paths and namespaces to match with your application.