Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a variable in Twig view pre render

Tags:

php

twig

silex

I'm using Twig in a silex application. In a pre request hook I'd like to check if a user is logged in and if they are add the user object to Twig (so I can render logged in / logged out state in the menu).

However having looked at the source code it looks like it's only possible to supply template view variables as an argument to the render method. Am I missing something here?

Here is exactly what I'd like to achieve:

// Code run on every request    

$app->before(function (Request $request) use ($app)
{
    // Check if the user is logged in and if they are
    // Add the user object to the view

    $status = $app['userService']->isUserLoggedIn();

    if($status)
    {
        $user = $app['userService']->getLoggedInUser();

        //@todo - find a way to add this object to the view 
        // without rendering it straight away
    }

});
like image 556
Ben Waine Avatar asked Nov 28 '22 02:11

Ben Waine


1 Answers

$app["twig"]->addGlobal("user", $user);
like image 67
Maerlyn Avatar answered Dec 08 '22 09:12

Maerlyn