Closed roobiniano closed 3 years ago
You can use the Twig addGlobal
method, for example:
$twig->addGlobal('current_user', \App\Auth::getUser());
As this is created in the Core/View class, you'd have to call the above line of code in there for example.
It works perfect if I call it from Core/View but it doesn't work (it doesn't give an error either) if I want to do it from the index.php prior to some environment validations and others. there is no way ?
im tryng this in index.php
$loader = new \Twig\Loader\FilesystemLoader(dirname(__DIR__) . '/App/Views');
$twig = new \Twig\Environment($loader);
$twig->addGlobal('aloha', 'hawaiiii');
To call addGlobal
you need access to the Twig environment variable that you create in the Core\View class - you can either create this object in the index.php script then pass this to the Core\View class so it uses the same one, or you could make the one in that class available as a property, e.g. in the Core\View class add a property for the $twig variable and use that instead of a variable in the method.
To call
addGlobal
you need access to the Twig environment variable that you create in the Core\View class - you can either create this object in the index.php script then pass this to the Core\View class so it uses the same one, or you could make the one in that class available as a property, e.g. in the Core\View class add a property for the $twig variable and use that instead of a variable in the method.
thanks dave, finally use the option to declare the object in the index and use the variable in the Core / View class and it works great.
Hi Dave, how are you? Is there a way to have global variables available in all templates, without the need to add it in every View instance? for example a variable that contains the data of the logged-in user, that is always available to consult that data, or a variable to be able to have the path to the static files, etc.