The layout is the very core component and represents the structure of a webpage design using an XML file, within which the User Interface control will be properly displayed.
When you feel the need to adjust some nice touches to your webpage with custom extensions and won’t dare to mess things up in Magento Core Files, overriding Magento base layout might be your best option available in this case.
The overriding function is also useful when the amount of customizations is large.
Here is the tutorial on how to override layouts in Magento 2.
Magento 2 layouts are divided into Base Layouts and Theme Layouts.
Base Layouts: layout files provided by modules. Conventional location:
- Page configuration and generic layout files:
<module_dir>/view/frontend/layout
- Page layout files:
<module_dir>/view/frontend/page_layout
Theme Layouts: provided by themes. Conventional location:
- Page configuration and generic layout files:
<theme_dir>/<Namespace>_<Module>/layout
- Page layout files:
<theme_dir>/<Namespace>_<Module>/page_layout
Override base layouts
The step to do here is very simple: You’ll have to create a local.xml file in the following location:
<theme_dir>
|__/<Namespace_Module>
|__/layout
|__/override
|__/base
|--<layout1>.xml
|--<layout2>.xml
This file will, therefore, override these layouts:
<module_dir>/view/frontend/layout/<layout1>.xml
<module_dir>/view/frontend/layout/<layout2>.xml
For example:
<theme_dir>/Magento_Checkout/layout/override/base/checkout_cart_index.xml
will override
Magento_Checkout/view/frontend/layout/checkout_cart_index.xml
Override theme layouts
On the other hand, if you want to override theme layouts, repeat the very step above, only this time you need to put your new layout file in this location:
<theme_dir>
|__/<Namespace_Module>
|__/layout
|__/override
|__/theme
|__/<Parent_Vendor>
|__/<parent_theme>
|--<layout1>.xml
|--<layout2>.xml
These files will override the layouts below:
<parent_theme_dir>/<Namespace>_<Module>/layout/<layout1>.xml
<parent_theme_dir>/<Namespace>_<Module>/layout/<layout2>.xml
For example:
You want to override this file:
app/design/frontend/Magento/luma/Magento_Checkout/layout/checkout_cart_index.xml
Then you need to create a file as below:
<theme_dir>/Magento_Checkout/layout/override/theme/Magento/luma/checkout_cart_index.xml
* To override page layout files, use the page_layout
directory name instead of layout
.
* Remember to always name your new layout files with the same name as the file that you wish to override.
To ensure you can override the layouts smoothly, we strongly recommend you not make the following changes:
- Changing block name or alias. The name of a block should not be changed, and neither should the alias of a block remaining in the same parent element.
- Changing handle inheritance. For example, you should not change the page type parent handle.