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 shown below:

twig: globals: var_name: var_value 

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

 {{var_name}} 

which will display

 var_value 

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

+6
source share
4 answers

There seems to be no way to capture a specific value. But you can get the full array of globals from the twig service, and then grab its offset.

 $twig = $this->container->get('twig'); $globals = $twig->getGlobals(); echo $globals['var_name']; 
+22
source

Good practice is to follow the official Twig global variable guide in the Symfony Cookbook . In practice, you should define a global variable that can be used in controllers, for example:

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

The variable is then defined as global for Twig templates.

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

Therefore, {{my_var}} will return HiAll, but you need to take care of the value once in the parameters.ini file.

So, the answer to the question: no! Or for sure, inefficient. MDrollette made the way possible!

+4
source

It was not clear to me whether you want to access the var branch in the controller or just access the global var from the configuration. Here's how to access global var from a configuration file ...

You can put the value in the configuration options section.

 parameters: var_name: some_value 

Now you can access it from the controller ...

 $value = $this->container->getParameter('var_name'); 
+2
source

I think you better use the package configuration or the DIC parameters for your value, and then add it to the global globules (for example, through the extension class of your package) and not try to do the opposite.

+2
source

Source: https://habr.com/ru/post/918097/


All Articles