Reputation: 17713
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?
Upvotes: 6
Views: 13099
Reputation: 17713
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!
Upvotes: 4
Reputation: 1186
I think you'd better to use bundle configuration or DIC parameters for your value, and then add it to the twig globals (via your bundle extension class, for example), and not trying to do the opposite.
Upvotes: 2
Reputation: 6927
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'];
Upvotes: 23
Reputation: 13972
I wasn't clear if you wanted to access the twig var in the controller, or just access a global var from the config. Here is how to access a global var from the config file...
You can place the value in the parameters section of the config..
parameters:
var_name: some_value
Now you can access it from the controller...
$value = $this->container->getParameter('var_name');
Upvotes: 2