超薄3 - 如何添加404模板?

lau*_*kok 5 slim psr-7 slim-3

在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');
});
Run Code Online (Sandbox Code Playgroud)

但在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');
    };
};
Run Code Online (Sandbox Code Playgroud)

如何添加我的404模板('404.html')?

Dav*_*ore 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"
        ]);
    };
};
Run Code Online (Sandbox Code Playgroud)

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

$app = new \Slim\App($container);
$app->run();
Run Code Online (Sandbox Code Playgroud)