Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slim 3 - How to add 404 Template?

Tags:

slim

psr-7

slim-3

In Slim 2, I can over write the default 404 page easily,

// @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');
});

But in 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');
    };
};

How can I add my 404 template ('404.html') in?

like image 339
Run Avatar asked Sep 19 '15 12:09

Run


1 Answers

Create your container:

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

Construct the \Slim\App object using the $container and run:

$app = new \Slim\App($container);
$app->run();
like image 124
Davide Pastore Avatar answered Oct 09 '22 21:10

Davide Pastore