Different layout file for different controller

2019-02-05 14:48发布

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?

3条回答
淡お忘
2楼-- · 2019-02-05 14:52

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楼-- · 2019-02-05 15:02
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',
    ),
),
查看更多
乱世女痞
4楼-- · 2019-02-05 15:12

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.

查看更多
登录 后发表回答