// Initialize Twig environment and template loader $loader = new Twig_Loader_Filesystem('/path/to/templates'); $twig = new Twig_Environment($loader, array()); // Add a global variable to Twig templates $twig->addGlobal('site_name', 'My Website'); // Render a template echo $twig->render('home.twig');
// Initialize Twig environment and template loader $loader = new Twig_Loader_Filesystem('/path/to/templates'); $twig = new Twig_Environment($loader, array()); // Add multiple global variables to Twig templates $twig->addGlobal('site_name', 'My Website'); $twig->addGlobal('author_name', 'John Doe'); $twig->addGlobal('footer_text', 'Copyright 2021'); // Render a template echo $twig->render('home.twig');This example shows how to add multiple global variables to Twig templates using the addGlobal method. These variables can be used in any template file just like in Example #1. The addGlobal method is part of the Twig package library, which is a popular template engine for PHP.