1

I've been using slim/twig-view, documented here: https://notes.enovision.net/slim/composer-package-documentation/slim_twig-view. The recommended way to handle a route, render a view is:

$app->get('/hello/{name}', function ($request, $response, $args) {
    $view = Twig::fromRequest($request);
    return $view->render($response, 'profile.html', [
        'name' => $args['name']
    ]);
})

Problem is, if you try to add any route based middleware to run afterwards, it fails

$app->get('/hello/{name}', function ($request, $response, $args) {
    $view = Twig::fromRequest($request);
    return $view->render($response, 'profile.html', [
        'name' => $args['name']
    ]);
})->add(function(Request $request, RequestHandler $handler){
    $response = $handler->handle($request);
    return $response;
});

With an error like this:

Type: TypeError
Code: 0
Message: Return value of Slim\Handlers\Strategies\RequestResponse::__invoke() must implement interface Psr\Http\Message\ResponseInterface, int returned
File: /var/www/html/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php
Line: 43

I see this is because I'm not returning a response from the route handler, so I rewrite the route handler to return the $response:

 $view = Twig::fromRequest($request);
    $view->render($response, 'profile.html', [
        'name' => $args['name']
    ]);
    return $response;

Still the same error.

I can work around this, but it's a greenfield project and it would be nice to have access to route middleware. Any ideas?

Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
  • Mhm, usually on Symfony you `return $view->render(...)` this is also what they do on the doc page you are linking – β.εηοιτ.βε Jun 23 '20 at 18:47
  • Seems to be true here too: `public function render(ResponseInterface $response, string $template, array $data = []): ResponseInterface` https://github.com/slimphp/Twig-View/blob/94bcc75e8044d0072e29b149f1be4967c12d0c1d/src/Twig.php#L200 – β.εηοιτ.βε Jun 23 '20 at 18:50
  • Do you have the same issue if you just do not chain the two? e.g. `$app->get(...); $app->add(...);` – β.εηοιτ.βε Jun 23 '20 at 18:59
  • It's only when I chain. – Robert Moskal Jun 23 '20 at 21:04
  • I like the way twig is used in here https://odan.github.io/2020/04/17/slim4-twig-templates.html – cssBlaster21895 Jun 23 '20 at 21:45
  • I copied the example from the link in your question in `index.php`, removed all its route definitions, added your route definition for `/hello/{name}` **with route middleware** and it just shows the expected result. Please provide more details, if possible, a full example would help a lot (i.e not only the route definition , but a simple full app like the link you provided) – Nima Jun 24 '20 at 03:40

0 Answers0