php - 在 Twig View 预渲染中设置变量

标签 php twig silex

我在 silex 应用程序中使用 Twig。在预请求 Hook 中,我想检查用户是否登录以及他们是否将用户对象添加到 Twig(这样我就可以在菜单中呈现登录/注销状态)。

然而,查看源代码后,它似乎只能提供模板 View 变量作为渲染方法的参数。我在这里错过了什么吗?

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

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

});

最佳答案

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

关于php - 在 Twig View 预渲染中设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10108057/

相关文章:

php - 当用户填写字段时减少相同输入的数量

php - 按名称 asc 排序时获取表中一行的位置

php - Mysql 和 PHP - 即使在 "utf8_general_ci"排序规则下,查询也找不到带有重音字符的关键字

forms - 调用 handleRequest 或 bind 时未找到 Silex ExecutionContext::getValidator()

php - 如何在提交时弹出联系表单在弹出窗口中显示确认消息?

php - 使用 Bootstrap 自定义集合

php - Symfony 表单集合 Twig 渲染

php - 使用 Symfony 表单上传多个文件

php - 替代 php silex 模板

json - Silex & phpunit JSON 响应