Magento 2 – Use Update Handle XML in Multiple Modules Layout

layoutlayout-updatemagento2update-handle

Within a Magento 2 theme, given an XML layout file such as the following, named for example, remove_header.xml:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
         <referenceContainer name="header-wrapper" remove="true" />
    </body>
</page>

How can I use <update handle="remove_header"/> in any module layout XML files in the theme?

The goal is to be able have the following layout XML:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
         <update handle="remove_header" />
    </body>
</page>

in both theme-stackoverflow/Magento_Catalog/layout/catalog_product_view.xml and theme-stackoverflow/Magento_Cms/layout/cms_index_index.xml

Without being able to that, I'd have to place remove_header.xml in theme-stackoverflow/Magento_Catalog/layout/ and theme-stackoverflow/Magento_Cms/layout/ which basically negates the point of having the update in a seperate XML file referenced via <update />

There's not an option to have a directory such as theme-stackoverflow/frontend/layout/ or similar that I've seen. I tried placing the referred to XML file in Magento_Theme so at theme-stackoverflow/Magento_Theme/layout/remove_header.xml and using <update /> exactly as shown above. It doesn't work.

So is this even possible or in this case, would you have to duplicate the layout XML?

Best Answer

OK, turns out placing the referred to XML file at theme-stackoverflow/Magento_Theme/layout/remove_header.xml does actually work. It was my placement of <update handle/> that was at fault. The layout update won't take place unless the node is top-level, so not a child of the <body> node.

Changing the second block of XML in the question to the following allows the solution to work:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <!-- Moved to here... -->
    <update handle="remove_header" />
    <body>
         <!-- ..from here -->
    </body>
</page>