问题
I'm using Twig and Slim4 with DI container (the same as this tutorial: https://odan.github.io/2019/11/05/slim4-tutorial.html). I would like to know how can I add a common model to all my twig views, for example user object, general options and something like this.
This is the container Twig initialization:
TwigMiddleware::class => function (ContainerInterface $container) {
return TwigMiddleware::createFromContainer($container->get(App::class), Twig::class);
},
// Twig templates
Twig::class => function (ContainerInterface $container) {
$config = $container->get(Configuration::class);
$twigSettings = $config->getArray('twig');
$twig = Twig::create($twigSettings['path'], $twigSettings['settings']);
return $twig;
},
The twig middleware is the Slim standard one: Slim\Views\TwigMiddleware
回答1:
You can add global variables to Twig environment, so they are accessible in all template files:
(To be able to provide a sample code, I assumed you have defined a service like user-authentication-service
which is capable of resolving current user)
// Twig templates
Twig::class => function (ContainerInterface $container) {
//...
$twig = Twig::create($twigSettings['path'], $twigSettings['settings']);
$twig->getEnvironment()->addGlobal(
'general_settings',
[
'site_name' => 'my personal website',
'contact_info' => 'me@example.com'
]);
$twig->getEnvironment()->addGlobal(
'current_user',
// assuming this returns current user
$container->get('user-authentication-service')->getCurrentUser()
);
return $twig;
},
Now you have access to general_settings
and current_user
in all of your template files.
来源:https://stackoverflow.com/questions/61119708/how-to-add-common-model-to-twig-and-slim4