Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework 2: Set Layout using MvcEvent

I want to change the layout using an mvc event. I've tried the following:

// $event instanceof \Zend\Mvc\MvcEvent
$serviceManager = $event->getApplication()->getServiceManager();
$controllerLoader = $serviceManager->get('ControllerLoader');
$controllerLoader->addInitializer(function ($controller) {

    $controller->layout('layout/example');
    // OR THIS
    $controller->getEvent()->getViewModel()->setTemplate('layout/example');
});

My aproaches don't produce any errors notices or something. Not even if layout/example doesn't exist. Why is it possible to change the layout from inside a controller with $this->layout() but not from outside with $controller->layout()?

I also tried it this way:

// $event instanceof \Zend\Mvc\MvcEvent
$serviceManager = $event->getApplication()->getServiceManager();
$renderingStrategy = $serviceManager->get('DefaultRenderingStrategy');
$renderingStrategy->setLayoutTemplate('layout/example');

This also does not throw out any errors but does not change anything.

How can I switch the layout from outside of the controller during runtime?

like image 879
Andreas Linden Avatar asked Jan 16 '23 17:01

Andreas Linden


1 Answers

aww, it was so easy: simply call it directly on the event..

// $event instanceof \Zend\Mvc\MvcEvent
$event->getViewModel()->setTemplate('layout/example');
like image 80
Andreas Linden Avatar answered Feb 02 '23 22:02

Andreas Linden