超薄3-如何添加404模板? [英] Slim 3 - How to add 404 Template?

查看:18
本文介绍了超薄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');
});

但在超薄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")?

推荐答案

创建容器:

// Create container
$container = new SlimContainer;

// Register component on container
$container['view'] = function ($c) {
    $view = new SlimViewsTwig('./public/template/');
    $view->addExtension(new SlimViewsTwigExtension(
        $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构造SlimApp对象并运行:

$app = new SlimApp($container);
$app->run();

这篇关于超薄3-如何添加404模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆