我正在学习使用超薄框架(v3),并且我一直试图使用flash消息进行重定向。我有一个主页URL和一个/ flash URI,它应该设置一条flash消息并重定向到home。
我的引导代码是:
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'));
});
我试图在树枝上使用这条消息:
{{ flash.getMessage('global')[0] }}
重定向正在发生,但Flash消息未传递到新位置。我做错了什么?
答案 0 :(得分:3)
更好的方法是使用中间件来获取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');
});
然后从View中调用它,
{{ flash.getMessage('global')[0] }}
答案 1 :(得分: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 }}