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

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.


As of this day, the class signature has changed. You must implement \ Twig_Extension_GlobalsInterface, without it, your globals won't show up.

class MyTwigExtension extends \Twig_Extension implements Twig_Extension_GlobalsInterface
{ }

Bye!


you can register a twig extension

services:
    twig_extension:
        class: Acme\DemoBundle\Extension\TwigExtension
        arguments: [@doctrine]
        tags:
            - { name: twig.extension }

And then in the TwigExtension you can do as follows:

class TwigExtension extends \Twig_Extension
{
    public function getGlobals() {
        return array(
            // your key => values to make global
        );
    }
}

So you could get a value from the database in this TwigExtension and pass it to the template with the getGlobals() function