Search code examples
error-handlingtwigsilex

When using the error handler in Silex, how do I render a twig template?


I am trying to figure out how to have the error handler in Silex render a twig template. This is what they provide in documentation:

$app->error(function (\Exception $e, Request $request, $code) {
    return new Response('We are sorry, but something went terribly wrong.');
});

What I wrote is:

 $app->error(function (\Exception $e, Request $request, $code) {
  return $app['twig']->render('error.twig');
});

I aslo tried:

$app->error(function (\Exception $e, Request $request, $code) {
    return new Response($app['twig']->render('error.twig'));
});

I couldn't find a manual that went through the methods I could have worked with in Silex and its error handling.


Solution

  • The variable app is not known inside the closure, you need to tell the closureto use it. This will you will have access to twig and you are able to render a template.

    $app->error(function (\Exception $e, Request $request, $code) use($app) {
      return $app['twig']->render('error.twig');
    });