How to render custom template and return proper status code?


Currently using Plates for my templates, and I’m trying to render a custom template for error pages.

I noticed that if I do this:
return $response->withStatus(404);

My application properly returns a response with a 404 status code. However, if I do either of these:
return $response->withStatus(404)->getBody()->write($template);
return $response->withStatus(404)->getBody()->write('testing');

My application incorrectly returns a response with a 200 status code:

Thanks in advance. I am doing this via a controller method whose parameters are:

Psr\Http\Message\ServerRequestInterface $req, Psr\Http\Message\ResponseInterface $res, array $args


I haven’t used Plates, so I’m not certain what might be happening there. But this app works fine in my environment and returns a 200 response. Can you reduce your example down to something simple like this?


require __DIR__ . '/../vendor/autoload.php';

// Create and configure Slim app
$config = ['settings' => [
    'addContentLengthHeader' => false,
$app = new \Slim\App($config);

// Define app routes
$app->get('/', function ($request, $response, $args) {
    return $response->withStatus(404)->getBody()->write('testing');

// Run app


You may have misread, and I might be misunderstanding the functionality of withStatus. Do you mean your example returns a 404 response and not a 200 response as you mentioned?

If you do return $response->withStatus(404); I would assume this returns a 404 response.

Either way, I believe I have solved my problem. This seems to have worked:
(Where $this->templates is an instance of League\Plates\Engine)

$template = $this->templates->render('TemplateFile', ['param' => $param]);
return $response->withStatus(404)->write($template);

I was under the assumption that you must ->getBody() before you can ->write() to the response, but this doesn’t seem to be the case. I’m not sure what the difference is, but using ->getBody() beforehand was not giving the proper response code. If anyone can shed light on this, that would be great.


Right, sorry, I misread. :flushed:

If you have a look at the write method on Response, it looks like it is a shortcut to getting the response’s body stream and writing to it, performing getBody() itself.