Magento2 Module Layout – Relationship Between Module Layout Handle XML Files and Theme Update XML Files

layoutmagento2moduletheme

What's the relationship between a module's layout handle XML file and a theme's layout handle XML file? Which files have priority? When does one file replace another file? When does one file merge with another file? I haven't been able to find concrete information on this in the documentation, and I'm hoping for a clear answer before I spend too much time hunting this information down myself.

That is, in Magento 2 it's possible for a module to add a layout handle XML file

vendor//magento/module-theme/view/frontend/layout/default.xml

It's also possible for a theme to specify this exact same layout handle XML file

vendor//magento/theme-frontend-blank/Magento_Theme/layout/default.xml 

and for a theme that inherits from another theme to specify the exact same file.

vendor//magento/theme-frontend-luma/Magento_Theme/layout/default.xml 

What's not clear is the relationship between all these files. In Magento 1, creating a new layout update XML file in a theme would replace that original layout update XML file. Early versions of Magento 2 featured layout merging, where new layout files would be merged with the originals. It's not clear if merging made it into Magento 2. If it did, it's not clear what those merging rules are. It's also not clear if a theme replacing a module file behaves differently than a child theme file replacing a parent theme file.

Short of tracing the very abstract and complicated merging code myself, does anyone know the rules for this new layout merging?

Best Answer

the order of layout files collecting is documented here under "Extend layouts" http://devdocs.magento.com/guides/v2.0/frontend-dev-guide/themes/theme-inherit.html

Extend layouts

The layouts processing mechanism does not involve fallback. The system collects layout files in the following order:

  1. Current theme layouts: /_/layout/
  2. Ancestor themes layouts, starting from the most distant ancestor, recursively until a theme with no parent is reached: /_/layout/
  3. Module layouts for the frontend area: /view/frontend/layout/
  4. Module layouts for the base area: /view/base/layout/

Unlike templates or images, layout can be not only overridden, but also extended. And the recommended way to customize layout is to extend it by creating theme extending layout files.

Related Topic