在Twig视图中设置变量预渲染

Ben*_*ine 4 php twig silex

我在一个silex应用程序中使用Twig.在预请求挂钩中,我想检查用户是否已登录,以及是否将用户对象添加到Twig(因此我可以在菜单中呈现登录/注销状态).

但是看过源代码后,它看起来只能提供模板视图变量作为render方法的参数.我在这里错过了什么吗?

这正是我想要实现的目标:

// 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
    }

});
Run Code Online (Sandbox Code Playgroud)

Mae*_*lyn 18

$app["twig"]->addGlobal("user", $user);
Run Code Online (Sandbox Code Playgroud)


igo*_*orw 15

除了Maerlyn所说的,你可以这样做:

$app['user'] = $user;
Run Code Online (Sandbox Code Playgroud)

在您的模板中使用:

{{ app.user }}
Run Code Online (Sandbox Code Playgroud)