Ben Waine Ben Waine - 7 months ago 64
PHP Question

Setting a variable in Twig view pre render

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
}

});

Answer
$app["twig"]->addGlobal("user", $user);