Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 658
Amir Ajoudanian Avatar asked Mar 10 '15 07:03

Amir Ajoudanian


People also ask

How do I add a global variable in Twig?

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.

How do you access variables in Twig?

In Twig templates variables can be accessed using double curly braces notation {{ variableName }} .

How do you add a global variable?

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.


2 Answers

Using Symfony configuration

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.


Using Twig_Environment::addGlobal

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.


Using a Twig template

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.

like image 89
Alain Tiemblo Avatar answered Oct 28 '22 01:10

Alain Tiemblo


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'
like image 34
frzsombor Avatar answered Oct 28 '22 02:10

frzsombor