如何在 slim 3 和 twig 中使用带有重定向的 flash 消息传递

How to use flash messaging with redirects in slim 3 and twig

我正在学习使用 slim 框架 (v3),但我一直在尝试使用 flash 消息进行重定向。我有一个 home URL 和一个 /flash URI,它应该设置一个 flash 消息并重定向到 home。

我的bootstrap代码是:

use Slim\App;
use Slim\Container;
use Slim\Flash;
$container = new Container(['settings' => ['displayErrorDetails' =>  true]]);
$container['view'] = function ($container) {
    $view = new \Slim\Views\Twig([
        INC_ROOT. '/app/views',
        INC_ROOT. '/app/views/templates',
        INC_ROOT. '/app/views/templates/partials',], [
            'debug' => true
        ]);
    $view->addExtension(new \Slim\Views\TwigExtension(
        $container['router'],
        $container['request']->getUri()
    ));

    $view->getEnvironment()->addGlobal('flash', $container['flash']);

    return $view;
};
$container['flash'] = function () {
    return new Flash\Messages();
};
$app = new App($container);

我的路由文件是:

$app->get('/', function($request, $response, $args){
    return $this->view->render($response, 'home.twig');
})->setName('home');

$app->get('/flash', function ($req, $res, $args) {
    // Set flash message for next request
    $this->flash->addMessage('global', 'This is a message');

    // Redirect
    return $res->withStatus(301)->withHeader("Location", $this->router->pathFor('home'));
});

我正在尝试将 twig 中的消息用作:

{{ flash.getMessage('global')[0] }}

重定向正在进行,但闪现消息没有传递到新位置。我做错了什么?

一个更好的方法是为 flash 消息使用一个中间件,那么你应该能够在你的 View 中访问 flash 消息,这样做..

//Add a middleware to your app
 $app->add(function ($request, $response, $next) {
   $this->view->offsetSet("flash", $this->flash);
   return $next($request, $response);
});

$app->get('/flash', function ($req, $res, $args) {
    // Set flash message for next request
    $this->flash->addMessage('global', 'This is a message');
    $this->view->render($res, 'home.twig');
});

然后像这样从视图中调用它,

{{ flash.getMessage('global')[0] }} 

我想你可以通过阅读Slim-Flash页来理解。

路由文件

$app->get('/', function($request, $response, $args){
    $messages = $this->flash->getMessages()['global'][0];
    return $this->view->render($response, 'home.twig', ['messages' => $messages]);
})->setName('home');

$app->get('/flash', function ($req, $res, $args) {
    // Set flash message for next request
    $this->flash->addMessage('global', 'This is a message');

    // Redirect
    return $res->withStatus(301)->withHeader("Location", $this->router->pathFor('home'));
});

树枝文件

{{ messages }}