5

在 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')?

4

2 回答 2

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();
于 2015-09-19T14:30:59.143 回答
2

选项1:

使用Twig(或任何其他模板引擎)

选项 2:

$notFoundPage = file_get_contents($path_to_404_html);
$response->write($notFoundPage);
于 2015-09-19T14:01:02.683 回答