Controller specific layout in ZendFramework 2

南笙酒味 提交于 2019-12-06 04:17:50

See akrabat's examples for a number of nice ways that layouts, views, etcetera can be tweaked easily.

Specifically what you're looking for can be found on his github here.

Here is a cut-paste of the controller's action method that sets/uses the alternate layout:

public function differentLayoutAction()
{
    // Use a different layout
    $this->layout('layout/different');

    return new ViewModel();
}

Edit: It looks like akrabat has an example that says Change the layout for every action within a module, which might give the best pointers for setting the layout in the config; but I just had a look at the code, and the example is currently unfinished, it's not changing the layout.

I can just point you into the right direction, since currently i'm unable to open a sample project. Evan Coury has posted a method for Module specific layouts. See the following links:

Module Specific Layouts in Zend Framework 2

<?php
namespace MyModule;

use Zend\ModuleManager\ModuleManager;

class Module
{
    public function init(ModuleManager $moduleManager)
    {
        $sharedEvents = $moduleManager->getEventManager()->getSharedManager();
        $sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
            // This event will only be fired when an ActionController under the MyModule namespace is dispatched.
            $controller = $e->getTarget();
            $controller->layout('layout/alternativelayout');
        }, 100);
    }
}

Now how would this help you?: Well, $controller should have both the called controller and action stored. I'm sure you can check the $controller for the called action and then assign the layout accordingly.

I'm sorry i can currently only hint you into the direction, but i'm sure this can get you started.

@Sam's answer pretty much answers the question. As stated it just needs a check on which controller is called, which can be done like this:

<?php
namespace MyModule;

use Zend\ModuleManager\ModuleManager;

class Module
{
    public function init(ModuleManager $moduleManager){
        $sharedEvents = $moduleManager->getEventManager()->getSharedManager();
        $sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
                $controller = $e->getTarget();
                if ($controller instanceof Controller\AltLayoutController) {
                    $controller->layout('layout/alternativelayout');
                }
            }, 100);
    }

I

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!