Pragmatism in the real world

Module specific layouts in ZF2

If you need different layout scripts to be rendered for different modules in Zend Framework 2, then Evan Coury has made this extremely easy. His new module EdpModuleLayouts is just the ticket!

Once installed, you simply have to add a new array to a config file in the config/autoload folder with the following in it:

array(
    'module_layouts' => array(
        'Application' => 'layout/application',
        'ZfcUser' => 'layout/user',
    ),
);

i.e. you provide a list of the module name against the layout script to use.

What could be easier?

UPDATE:
For information on how this works, Evan’s post explains more.

8 thoughts on “Module specific layouts in ZF2

  1. Why is this not possible this way by default in ZF2? (instead of registering a listener and changing it in module.php)

  2. Mushfig,

    The operation is relatively straightforward. The module registers a event listener on ZendMvcControllerAbstractActionController's dispatch event. When it is triggered, the listener works out the current module's namespace and if the namespace is a key within the module_layouts config then the layout is changed.

    Youri,

    Zend Framework 2 is designed to be extended with single purpose modules so that the core doesn't have to have every feature.

    Regards,

    Rob…

  3. To me it makes more sense to have a module be responsible for it's own layout script, otherwise you end up setting the layout every time you use the module. Being able to override or decorate through DI does sound nice though.

  4. I think you can have the best of both worlds now, if you install Evan's module (or list that as a dependency of your own module if it's redistributable):
    – Use Evan's module
    – Put the layout config for your module in your module. It will be merged into a shared 'module_layouts' config.

    Benefits:
    – You write little configuration, because you reuse Evan's module
    – Your module is responsible for it's own layout.

    I did not try yet, but I think it should work this way.

Comments are closed.