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

Lau*_*ura 2 php slim

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

我通常在每个模板中都有一些我想要的变量(比如用户名,日期等).在Slim v2中,我曾经通过使用一个钩子然后调用setData或appendData方法来做到这一点:

$app->view->setData(array(
    'user' => $user
));
Run Code Online (Sandbox Code Playgroud)

H3已被v3中的Middlewares取代,但我不知道如何在全局模板上设置数据 - 所有模板 - 任何想法?

小智 8

这实际上是根据您正在使用的视图组件,Slim 3项目提供了2个组件Twig-ViewPHP-View

对于Twig-View,你可以使用offsetSet,这是一个基本的用法示例,我将使用那个例子,但是有一个额外的行将foo变量设置到视图中

$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;
};
Run Code Online (Sandbox Code Playgroud)

您只需使用即可在Twig模板中访问它

{{ foo }}
Run Code Online (Sandbox Code Playgroud)

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

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

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

// or individually
$phpView->addAttribute($key, $value);
Run Code Online (Sandbox Code Playgroud)


geg*_*eto 5

对于树枝视图

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