在Slim 2中,我可以轻松覆盖默认的404页面,
// @ref: http://help.slimframework.com/discussions/problems/4400-templatespath-doesnt-change
$app->notFound(function () use ($app) {
$view = $app->view();
$view->setTemplatesDirectory('./public/template/');
$app->render('404.html');
});
但是在Slim 3中,
// ref: http://www.slimframework.com/docs/handlers/not-found.html
//Override the default Not Found Handler
$container['notFoundHandler'] = function ($c) {
return function ($request, $response) use ($c) {
return $c['response']
->withStatus(404)
->withHeader('Content-Type', 'text/html')
->write('Page not found');
};
};
如何在?
中添加我的404模板(' 404.html')答案 0 :(得分:15)
创建容器:
// Create container
$container = new \Slim\Container;
// Register component on container
$container['view'] = function ($c) {
$view = new \Slim\Views\Twig('./public/template/');
$view->addExtension(new \Slim\Views\TwigExtension(
$c['router'],
$c['request']->getUri()
));
return $view;
};
//Override the default Not Found Handler
$container['notFoundHandler'] = function ($c) {
return function ($request, $response) use ($c) {
return $c['view']->render($response->withStatus(404), '404.html', [
"myMagic" => "Let's roll"
]);
};
};
使用\Slim\App
构建$container
对象并运行:
$app = new \Slim\App($container);
$app->run();
答案 1 :(得分:2)
使用Twig(或任何其他模板引擎)
$notFoundPage = file_get_contents($path_to_404_html);
$response->write($notFoundPage);