Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 567
user4271704 Avatar asked Jan 15 '15 14:01

user4271704


4 Answers

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.

like image 175
Alain Tiemblo Avatar answered Oct 31 '22 04:10

Alain Tiemblo


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!

like image 29
Ousret Avatar answered Oct 31 '22 03:10

Ousret


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

like image 2
René Avatar answered Oct 31 '22 04:10

René


Stay away from global variables.

Instead make a custom twig extension then inject the database connection as a parameter.

Something like:

services:
    acme.twig.acme_extension:
        class: Acme\DemoBundle\Twig\AcmeExtension
        arguments: [@doctrine.dbal.default_connection]
        tags:
            - { name: twig.extension }

Details:

http://symfony.com/doc/current/cookbook/templating/twig_extension.html

like image 2
Tek Avatar answered Oct 31 '22 04:10

Tek