Different layout file for different controller

2019-02-05 14:39发布

问题:

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?

回答1:

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',
    ),
),


回答2:

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



回答3:

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.