'How can I define global variables inside a twig template file?
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.
Solution 1:[1]
It seems that you can assign global READONLY variables in your top-level template and use them in all underlying templates. But you can't override them of course. It covers my case, maybe will be useful for somebody else.
base.html.twig
<!DOCTYPE html>
{# assign global vars here #}
{% set myReadonlyJar = your_custom_ext_twig_function() %}
<html>
<body>
{% block body %}{% endblock %}
</body>
</html>
my_page.twig
{% extends 'stack/base.html.twig' %}
{% block body %}
{{ myReadonlyJar.v1 }}
{{ myReadonlyJar.v2 }}
{{ include('stack/deep.twig') }}
{% endblock %}
deep.twig
Check top vars very deep inside: <br>
{{ myReadonlyJar.v2 }}
Solution 2:[2]
Since Symfony 4, you can set the globals in config/packages/twig.yaml.
# config/packages/twig.yaml
twig:
# ...
globals:
ga_tracking: 'UA-xxxxx-x'
Solution 3:[3]
Using SlimFramework and Twig-View:3.0
You can use the following method Twig::offsetSet
$twig = Twig::create('view/templates');
$twig->offsetSet('globalVar', 'globalVarValue');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yehor |
| Solution 2 | |
| Solution 3 | SamHoque |
