Slim 3 - Как добавить шаблон 404?

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


person laukok    schedule 19.09.2015    source источник


Ответы (2)


Создайте свой контейнер:

// 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();
person Davide Pastore    schedule 19.09.2015
comment
Спасибо за ответ. - person laukok; 19.09.2015
comment
При возврате визуализированного представления для notFoundHandler, вероятно, лучше всего установить статус ответа на 404: $ response- ›withStatus (404) - person dotism; 24.10.2016
comment
@ethet Спасибо за комментарий, я обновил свой ответ. - person Davide Pastore; 24.10.2016

Опция 1:

используйте Twig (или любой другой шаблонизатор)

Вариант 2:

$notFoundPage = file_get_contents($path_to_404_html);
$response->write($notFoundPage);
person Martin    schedule 19.09.2015