This article explains how to set global variables for Twig using Symfony.
Based on the manual, I believe this method should also work with other versions.
SETTING GLOBAL VARIABLES IN THE CONFIG FILE.
Basically, you can set it up by simply adding it to your config file as shown below.
# app/config/config.yml
twig:
globals:
main_color: 'red'
...
# sample twig
{{ dump(main_color) }}
// result redIt's very simple. Of course, you can also use parameters from the service container.
# Using Service Container Parameters
# app/config/parameters.yml
parameters:
main_color: 'red'
# app/config/config.yml
twig:
globals:
main_color: '%main_color%'WHAT IF YOU WANT GLOBAL VARIABLES TO BE DYNAMIC INSTEAD OF FIXED?
You can control the values of global variables by setting a service to them.
// ColorDefine.php
...
class ColorDefine
{
public function getColor($main)
{
$color = $main;
return $color;
}
}
# app/config/config.yml
twig:
globals:
# To define a service as a global Twig variable, prefix the string with @.
main_color: '@AppBundle\Service\ColorDefine'
# twig
{{ dump(main_color.getColor('green')) }}
result greenAs shown above, it becomes possible to call a service directly in Twig.
You can also pass arguments, which I think offers high extensibility. However, there's a caveat: since it's set globally, the Service will be loaded even if it's not explicitly used in Twig.
Recommended Symfony Books
There aren't many varieties, and the framework itself has a vast amount of information, so even introductory books can be quite substantial reads.
RECOMMENDED TWIG BOOKS
I haven't read any books specifically dedicated to Twig, but I found some on Amazon Kindle.
📦