Slim 3 - 如何添加 404 模板?

Slim 3 - How to add 404 Template?

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

选项 1:

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

选项 2:

$notFoundPage = file_get_contents($path_to_404_html);
$response->write($notFoundPage);

创建您的容器:

// 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"
        ]);
    };
};

使用$container和运行构建\Slim\App对象:

$app = new \Slim\App($container);
$app->run();