如何将通用模型添加到 Twig 和 Slim4 [英] How to add common model to Twig and Slim4
问题描述
我将 Twig 和 Slim4 与 DI 容器一起使用(与本教程相同:https://odan.github.io/2019/11/05/slim4-tutorial.html).我想知道如何将通用模型添加到我所有的树枝视图中,例如用户对象、常规选项等.
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.
这是容器 Twig 初始化:
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;
},
twig 中间件是 Slim 标准的中间件:Slim\Views\TwigMiddleware
The twig middleware is the Slim standard one: Slim\Views\TwigMiddleware
推荐答案
您可以将全局变量添加到 Twig 环境中,以便在所有模板文件中都可以访问它们:
You can add global variables to Twig environment, so they are accessible in all template files:
(为了能够提供示例代码,我假设您已经定义了一个像 user-authentication-service
这样能够解析当前用户的服务)>
(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;
},
现在您可以访问所有模板文件中的 general_settings
和 current_user
.
Now you have access to general_settings
and current_user
in all of your template files.
这篇关于如何将通用模型添加到 Twig 和 Slim4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!