How to define a global variable for Twig

I use a file that serves as a form layout for overwriting certain elements (form_start, form_row, etc.). I will register it as:

twig: - AcmeMainBundle:Form:formlayout.html.twig 

Is there a way to use my variables in it along with the form ?

For example, when I submit index.html.twig

 array ('form' => $formView, 'var' => $var); 

Var is defined only in index.html.twig .

So how to make var in formlayout.html.twig

+7
php symfony twig
source share
3 answers

You can use the addGlobal() method.

For example, in BaseController I use:

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

therefore, in your case, you should probably:

 $this->get('twig')->addGlobal('var', $var); 
+27
source share

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

  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)), ); } } 

Hope that helps

World

+2
source share

In case you do not use a symphony, but use a branch on it, it is simple:

 <?php $loader = new \Twig_Loader_Filesystem('path/to/templates'); $twig = new \Twig_Environment($loader); $twig->addGlobal('key1', 'var1'); $twig->addGlobal('key2', 'var2'); 
+1
source share

All Articles