Skip to content

Instantly share code, notes, and snippets.

@kimausloos
Created March 1, 2014 22:05
Show Gist options
  • Select an option

  • Save kimausloos/9298197 to your computer and use it in GitHub Desktop.

Select an option

Save kimausloos/9298197 to your computer and use it in GitHub Desktop.
In Silex, we can use an KernelEvents::VIEW eventlistener to catch the event that's triggered when a non Response object is returned by the controller. We can then fetch the controller from the request, generate a path to a view and render that. That way we can just return an array() in the controller method and still get a nice html view, just l…
{# Thanatos/Hello/hello.html.twig #}
Hi there {{ name }}!
<?php
namespace Thanatos\Controller;
class HelloController
{
public function helloAction($name)
{
return array(
'name' => $name,
);
}
}
<?php
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpFoundation\Response;
$app->get('/hello/{name}', 'Thanatos\Controller\HelloController::helloAction');
$dispatcher = $app['dispatcher'];
$dispatcher->addListener(KernelEvents::VIEW, function(GetResponseForControllerResultEvent $event) use ($app) {
$controller = $app['request']->get('_controller');
$viewPath = strtr($controller, array(
'Controller' => '',
'Action' => '',
'::' => '/',
'\\' => '/',
));
$viewPath .= '.html.twig';
$response = new Response($app['twig']->render($viewPath, $event->getControllerResult()));
$event->setResponse($response);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment