Is it possible to set global variables in a twig file, so that I can access that variables from other files, macros and blocks.
For example, I want to have variables.twig
file and in it set my variables and then I can include it in other templates.
I know that setting global variables is possible from the framework (e.g. Symfony) but I want a solution using twig features only.
If you are using Twig in another project, you can set your globals directly in the environment: $twig = new Twig_Environment($loader); $twig->addGlobal('myStuff', $someVariable); And then use {{ myStuff }} anywhere in your application.
In Twig templates variables can be accessed using double curly braces notation {{ variableName }} .
The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
If you are using Symfony2+, you can set globals in your config.yml
file:
# app/config/config.yml
twig:
# ...
globals:
myStuff: %someParam%
And then use {{ myStuff }}
anywhere in your application.
If you are using Twig in another project, you can set your globals directly in the environment:
$twig = new Twig_Environment($loader);
$twig->addGlobal('myStuff', $someVariable);
And then use {{ myStuff }}
anywhere in your application.
When you're including a piece of Twig code, you're only including the rendered view coming from that code, not the code itself. So it is by design not possible to include a set of variables the way you are looking for.
Since Symfony 4, the you can set the globals in config/packages/twig.yaml
.
# config/packages/twig.yaml
twig:
# ...
globals:
ga_tracking: 'UA-xxxxx-x'
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