Using Symfony2 Configuration
If you use Symfony2, you can set global variables in the config.yml file:
# app/config/config.yml twig:
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.
source share