在 Slim v3 中全局设置模板数据

Set template data globally in Slim v3

我最近开始使用版本 3 中更新的 Slim 框架构建一个新应用程序。

我通常有一些我希望在每个模板中可用的变量(如用户名、日期等)。在 Slim v2 中,我曾经通过使用钩子然后调用 setData or appendData 方法来做到这一点,如下所示:

$app->view->setData(array(
    'user' => $user
));

挂钩已被 v3 中的中间件取代,但是我不知道如何为所有模板全局设置视图上的数据 - 有什么想法吗?

这确实是根据您使用的 view 组件,Slim 3 项目提供 2 个组件 Twig-View and PHP-View

对于Twig-View,可以使用offsetSet,这是一个基本的usage example,我去使用该示例,但增加一行以将 foo 变量设置为 view

$container['view'] = function ($c) {
    // while defining the view, you are passing settings as array
    $view = new \Slim\Views\Twig('path/to/templates', [
    'cache' => 'path/to/cache'
    ]);

    // Instantiate and add Slim specific extension
    $basePath = rtrim(str_ireplace('index.php', '', $c['request']->getUri()->getBasePath()), '/');
    $view->addExtension(new Slim\Views\TwigExtension($c['router'], $basePath));

    //////////////////////////////
    // this is my additional line
    $view->offsetSet('foo', 'bar');
    //////////////////////////////

    return $view;
};

您只需使用

即可在 Twig 模板中访问它
{{ foo }}

对于PHP-View,它有不同的传递变量到模板的形式,你可以在here

中找到它们
// via the constructor
$templateVariables = [
    "title" => "Title"
];
$phpView = new PhpRenderer("./path/to/templates", $templateVariables);

// or setter
$phpView->setAttributes($templateVariables);

// or individually
$phpView->addAttribute($key, $value);

对于树枝视图

$view->getEnvironment()->addGlobal($name, $value);