Created
March 1, 2014 22:05
-
-
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…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {# Thanatos/Hello/hello.html.twig #} | |
| Hi there {{ name }}! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace Thanatos\Controller; | |
| class HelloController | |
| { | |
| public function helloAction($name) | |
| { | |
| return array( | |
| 'name' => $name, | |
| ); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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