How to add common model to Twig and Slim4

痞子三分冷 提交于 2021-02-15 07:40:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!