ZF2 different layouts in modules

To enable a different layout in a module, to your module.php for the module define a new layout like so

public function init(ModuleManager $mm)
    {
        $mm->getEventManager()->getSharedManager()->attach(__NAMESPACE__, 'dispatch', function($e) {
            $e->getTarget()->layout('admin/layout');
        });
    }

then within your module.config.php view_manager settings define the template

'view_manager' => array(
        'template_map' => array(
            'admin/layout'           => __DIR__ . '/../view/layout/cms.phtml',
        ),
        'template_path_stack' => array(
            __DIR__ . '/../view',
        ),
    ),

or you can define a direct path in your module.php without any template mapping i.e

public function init(ModuleManager $mm)
    {
        $mm->getEventManager()->getSharedManager()->attach(__NAMESPACE__, 'dispatch', function($e) {
            $e->getTarget()->layout('layout/admin');
        });
    }

This will load module/view/layout/admin.phtml when this module is run

VN:F [1.9.9_1125]
Rating: 6.1/10 (8 votes cast)
VN:F [1.9.9_1125]
Rating: +2 (from 4 votes)
ZF2 different layouts in modules, 6.1 out of 10 based on 8 ratings

16,435 views

This entry was posted on Tuesday, June 4th, 2013 at 4:52 pm and is filed under Php, ZF2. You can follow any responses to this entry through the RSS 2.0 feed.

5 Responses to “ZF2 different layouts in modules”

  1. Zhabba says:

    Thanks a lot!
    Pretty clear.

    VA:F [1.9.9_1125]
    Rating: 1.0/5 (1 vote cast)
    VA:F [1.9.9_1125]
    Rating: +1 (from 1 vote)
  2. Yoppy Yunhasnawa says:

    It works, but why the URL from function $this->url() at layout still relative to other module?

    VA:F [1.9.9_1125]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.9_1125]
    Rating: 0 (from 0 votes)
    • Adrian says:

      Check your routing 🙂

      VN:F [1.9.9_1125]
      Rating: 0.0/5 (0 votes cast)
      VN:F [1.9.9_1125]
      Rating: 0 (from 0 votes)
  3. Azhar says:

    it gives me an error?

    Argument 1 passed to Login\Module::init() must be an instance of Login\ModuleManager, instance of Zend\ModuleManager\ModuleManager given, called in C:\xampp\htdocs\mvczend\vendor\zendframework\zendframework\library\Zend\ModuleManager\Listener\InitTrigger.php on line 33 and defined

    VA:F [1.9.9_1125]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.9_1125]
    Rating: 0 (from 0 votes)
  4. Venkat says:

    Thanks a lot !! Easy one and Working fine.

    VA:F [1.9.9_1125]
    Rating: 5.0/5 (1 vote cast)
    VA:F [1.9.9_1125]
    Rating: +1 (from 1 vote)

Leave a Reply