Search code examples
twigslim-4

How to add common model to Twig and Slim4


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


Solution

  • 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' => '[email protected]'
            ]);
        $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.