gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:23:32 26 4
gpt4 key购买 nike

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

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

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

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

最佳答案

这确实是根据您正在使用的 View 组件,Slim 3 项目提供2 个组件Twig-ViewPHP-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);

关于php - 在 Slim v3 中全局设置模板数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37643556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com