I'm working with Slim 3 and for rendering I'm using PHP-View . I'm iniating the renderer like this:
...
$container['view'] = new \Slim\Views\PhpRenderer("../mytemplatesfolder/");
$app = new \Slim\App();
$container = $app->getContainer();
$container['renderer'] = new PhpRenderer("templates");
I can render the templates without any problem in my routes, like this:
$app->get('/someroute', function (Request $request, Response $response){
return $this->renderer->render($response, "/onetemplate.phtml");
});
How can I render a custom template (using PHP-View, not Twig) when the 404 error happens?
I found this answer using Twig, but I can't figure it out how to to do it using PHP-View.
Given that you have a composer.json like that:
{
"require": {
"slim/slim": "^3.0",
"slim/php-view": "^2.2"
}
}
Here it is an example application:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Slim\Views\PhpRenderer;
require '../vendor/autoload.php';
$app = new \Slim\App;
$container = $app->getContainer();
$container['renderer'] = new PhpRenderer("./templates");
$container['notFoundHandler'] = function ($container) {
return function ($request, $response) use ($container) {
return $container['renderer']->render($response, "/404.php");
};
};
$app->get('/hello/{name}', function (Request $request, Response $response) {
$name = $request->getAttribute('name');
$response->getBody()->write("Hello, $name");
return $response;
});
$app->run();
And here it is the 404.php template (please notice that it is placed under the /templates
subfolder as specified in app.php
):
<?php
echo 'CONTENT NOT FOUND';
:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.