How to define global variable for Twig

In case you don't use symphony but use twig on it's own, it is as simple as:

<?php

$loader = new \Twig_Loader_Filesystem('path/to/templates');
$twig = new \Twig_Environment($loader);
$twig->addGlobal('key1', 'var1');
$twig->addGlobal('key2', 'var2');

You can use addGlobal() method.

For example in BaseController I use:

$this->get('twig')->addGlobal('is_test', $isTest);

so in your case you should probably do:

$this->get('twig')->addGlobal('var', $var);

To set a global variable in Twig I created a service call "@get_available_languages" (return an array) and then on my kernel.request event class I implemented the below:

  class LocaleListener implements EventSubscriberInterface
{
    private $defaultLocale;

    public function __construct($defaultLocale = 'en',       ContainerInterface $container)
    {
        $this->defaultLocale = $defaultLocale;
        $this->container = $container;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        //Add twig global variables
        $this->addTwigGlobals();


    }



    public function addTwigGlobals(){

        //Add avaialble language to twig template as a global variable
        $this->container->get('twig')->addGlobal('available_languages', $this->container->get('get_available_languages'));

    }

    public static function getSubscribedEvents()
    {
        return array(
            // must be registered before the default Locale listener
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
        );
    }
}

Tags:

Php

Twig

Symfony