如何在Slim 3.5中为Twig添加全局变量?


How can I add global variables for Twig in Slim 3.5?

在Symfony中,我习惯在任何视图中使用{{ app.user.username }}。我能在斯利姆做这样的事吗?

目前我正在将用户添加到$container['user']并将其传递给view->render($response, 'index.html.twig', ['user' => $this->user])的每个视图。

换句话说,我可以添加user作为Twig的全局变量吗?我看到许多类似的问题,但没有一个解决方案,我可以使用。

$container['view']->addGlobal('user', $this->user);呢?

我用它来暴露{{current_path}}变量中的路径:

$container = $app->getContainer();
$container["view"] = function ($container) use ($menu) {
    $view = new 'Slim'Views'Twig("../templates");
    $basePath = rtrim(str_ireplace("index.php", "", $container["request"]->getUri()->getBasePath()), "/");
    $view->addExtension(new Slim'Views'TwigExtension($container["router"], $basePath));
    $view->getEnvironment()->addGlobal("current_path", $container["request"]->getUri()->getPath());
    return $view;
};

遵循模板文档中描述的方法。

我通过将这行添加到我的依赖项(在我注册Twig之后)

$container['view']['user'] = $_SESSION['user'];

这个效果很好。我可以用{{ user.username }}获得用户名。我不知道以这种方式进行会话有多安全,但它是有效的。