Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a global variable for a Twig template available inside a Symfony2 controller?

A global variable for a Twig template can be defined inside the config.yml of a Symfony2 application as in the following:

twig:                 
    globals:
      var_name: var_value

Hence, in each Twig template the variable can be used as follows:

{{var_name}}

that will display

var_value

Do you know such a way to get the value of a global variable just inside a Symfony2 controller?

like image 742
JeanValjean Avatar asked Jun 14 '12 13:06

JeanValjean


2 Answers

There doesn't seem to be a way to grab a particular value. But you can get the full array of globals from the twig service and then grab it's offset.

$twig = $this->container->get('twig');
$globals = $twig->getGlobals();
echo $globals['var_name'];
like image 172
MDrollette Avatar answered Sep 30 '22 11:09

MDrollette


The right practice is to follow the official tutorial about Twig global variables in the Symfony's Cookbook. In practice, one should define a global variable that can be used in the controllers, e.g.:

  ; app/config/parameters.ini
  [parameters]
     my_global_var: HiAll

Then the variable is defined as global for the Twig templates

# app/config/config.yml
twig:
    globals:
        my_var: %my_global_var%

Hence, {{my_var}} will return HiAll but one should take care of the value once in the parameters.ini file.

So, the answer to the question is no! Or precisely, not in an effective way. MDrollette drawn a possible way!

like image 39
JeanValjean Avatar answered Sep 30 '22 12:09

JeanValjean