【问题标题】:Slim 3 - How to add 404 Template?Slim 3 - 如何添加 404 模板?
【发布时间】:2015-12-16 13:20:03
【问题描述】:

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

【问题讨论】:

    标签: slim slim-3 psr-7


    【解决方案1】:

    创建你的容器:

    // 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();
    

    【讨论】:

    • 当返回 notFoundHandler 的渲染视图时,最好将响应状态设置为 404:$response->withStatus(404)
    • @ethet 感谢您的评论,我已经更新了我的答案。
    【解决方案2】:

    选项 1:

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

    选项 2:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      • 2015-02-27
      • 2016-08-20
      相关资源
      最近更新 更多