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?
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'];
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With