How to Extend Layout

In Magento 2, you will have to work with the layout frequently. Layout customization includes multiple tasks that help you change any elements in your pages. To customize your layout, create extending and overriding layout files in your custom theme. All of these tasks can be done easily.

In today’s article, I will show you how to extend a layout in Magento 2.

How to Extend Layout in Magento 2 in 2 steps:

Step 1: Create theme extending file

In the system of Magento 2, instead of going through various steps including copping extensive page layout or page configuration code, modifying things you want to change, you can just create an extending layout file which has all the changes that you want to make.

Add extending page configuration or generic layout file

For an extending page configuration or generic layout file be added, the layout need to be place in the below location:

<theme_dir>
 |__/<Namespace>_<Module>
   |__/layout
     |--<layout1>.xml
     |--<layout2>.xml

Here is an example, if you want to customize the layout which is defined in <Magento_Catalog_module_dir>/view/frontend/layout/catalog_product_view.xml, a layout file that has the same name need to be added in your custom theme, for example, <theme_dir>/Magento_Catalog/layout/catalog_product_view.xml

Add extending page layout file

For an extending page layout file to be added, you need to put that file in the location down here:

<theme_dir>
 |__/<Namespace>_<Module>
   |__/page_layout
     |--<layout1>.xml
     |--<layout2>.xml

Step 2: Processing extending layouts

Following is how Layout files are merged by Magento:

  1. For each layout file which is included in the list:
    • Layout handle declaration and layout instructions are loaded.
    • The result is appended in the following format:
<layouts xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <handle id="checkout_cart_index" label="Shopping Cart" type="page" parent="default">
        <!-- Layout instructions from checkout_cart_index.xml -->
    </handle>
    <handle id="checkout_onepage_index" label="One Page Checkout" type="page" parent="default">
        <!-- Layout instructions from checkout_onepage_index.xml -->
    </handle>
    <!-- ... -->
</layouts>

The corresponding layout file’s name defines a handle ID, and the the root layout node’s attributes of this layout file define handle attributes.

  1. Finally, replace the base URL placeholders in the result.

Conclusion

Above, I have just provided two steps on how to extend a layout in Magento 2. Hope this post is helpful for you. If you have any questions or new ideas, feel free to leave a comment below.

Thank you for reading!

Enjoyed the tutorial? Spread it to your friends!