How to define global variables inside twig template file?

Is it possible to set global variables in a twig file so that I can access these variables from other files, macros and blocks.

For example, I want to have a variables.twig file, and my variables are set in it, and then I can include it in other templates.

I know that setting global variables is possible from a framework (like Symfony), but I want a solution that uses only twig functions.

+6
source share
1 answer

Using Symfony2 Configuration

If you use Symfony2, you can set global variables in the 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 use Twig in another project, you can set your global variables directly in the environment:

 $twig = new Twig_Environment($loader); $twig->addGlobal('myStuff', $someVariable); 

And then use {{ myStuff }} anywhere in your application.


Using the Twig Extension

If you have many global variables and you want to specify a set of global variables only for a specific part of your application, you can create a Twig extension:

 class Some_Twig_Extension extends Twig_Extension implements Twig_Extension_GlobalsInterface { public function getGlobals() { return array( 'someStuff' => $this->myVar, // ... ); } // ... } 

Then import it into your environment only if necessary:

 $twig = new Twig_Environment($loader); $twig->addExtension(new Project_Twig_Extension()); 

And still use {{ myStuff }} anywhere in the application.

Using Twig Template

When you include a piece of Twig code, you include only the display view coming from that code, not the code itself. Thus, by design, it is impossible to include a set of variables the way you are looking.

+17
source

Source: https://habr.com/ru/post/983576/


All Articles