Frage

How to make my ZF2 module load other layout file for specific controller ?

Consider you have IndexController and AdminController in your ZF2 application module and the IndexController is using layout.phtml but you want to use adminlayout.phtml for AdminController.

How is it possible?

War es hilfreich?

Lösung

class Module {
    public function onBootstrap($e) {
        $em  = $application->getEventManager();

        $em->attach(MvcEvent::EVENT_DISPATCH, function($e) {
            $controller = $e->getTarget();
            if ($controller instanceof Controller\AdminController) {   
                $controller->layout('layout/layoutadmin.phtml');
            } else {
                $controller->layout('layout/layout.phtml');
            }   
        });
    }
}

and don't forget to register your new controller by adding this config in your module config file:

'controllers' => array(
    'invokables' => array(
        'Application\Controller\Index' => 'Application\Controller\IndexController',
        'Application\Controller\Admin' => 'Application\Controller\AdminController',
    ),
),

Andere Tipps

other best Solution :

'view_manager' => array(
        'template_path_stack' => array(
            'YOURMODULENAME' => __DIR__ . '/../view',
        ),

        'template_map' => array(
            'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
        ),
    ),

change YOURMODULENAME to your module specific name

Rather than adding logic to your entire module in the onBootstrap method, you can use your controller's onDispatch method to simply set the layout for that entire controller.

In your admin controller, add a shortcut at the top:

use Zend\Mvc\MvcEvent;

Then, use the following onDispatch in your controller:

public function onDispatch(MvcEvent $mvcEvent)
{   
    $this->layout()->setTemplate('layout/admin');

    return parent::onDispatch($mvcEvent);
}

I believe this solution is better because the code only gets called when the admin controller is called.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top