$twig = new Twig_Environment($loader); $globalVars = array( 'site_name' => 'My Website', 'site_url' => 'https://www.example.com' ); $twig->mergeGlobals($globalVars); $tpl = $twig->load('page.html.twig'); echo $tpl->render(array( 'pageTitle' => 'Homepage', 'content' => 'Welcome to my website!' ));
class MyTwigEnvironment extends Twig_Environment { public function __construct(Twig_LoaderInterface $loader, array $options = array()) { parent::__construct($loader, $options); // Add some global variables $globalVars = array( 'site_name' => 'My Website', 'site_url' => 'https://www.example.com' ); $this->mergeGlobals($globalVars); } }In this example, we create a new class that extends the Twig_Environment class, and also adds some global variables to the environment during construction. This class can be used throughout the application instead of creating a new Twig_Environment instance each time. Package Library: Symfony/Twig-Bridge.