Magento how can override layout files

Different from Magento 1 layout files will be overwritten in the same way as overriding templates files, with Magento 2 doing so is considered an expanded layout. That is what makes Magento 2 layout more flexible but not in all cases is it possible to use the layout extension method to make customizations. If the amount of customization is large, that will become complicated and at this time completely overwriting the original file is an optimal choice. The question now is Magento how can override layout file.

This means that the new file that you place in the theme will be used instead of the parent theme layout file or base layout file.

1. How to override a layout

Override base layouts

if you want to override the following layouts:

   <module_dir>/view/frontend/layout/<layout1>.xml
   <module_dir>/view/frontend/layout/<layout2>.xml

Copy that file and place it in the following location and then edit it:

├── <Namespace_Module>/
│   ├── layout/
│   │   ├── override/
│   │   │   ├── base/
│   │   │   │	├── <layout1>.xml
│   │   │   │	├── <layout2>.xml

For example: Magento_Catalog/view/frontend/layout/catalog_product_view.xml will be override by <theme_dir>/Magento_Catalog/layout/override/base/catalog_product_view.xml

Override theme layouts

if you want to override the following layouts:

   <parent_theme_dir>/<Namespace>_<Module>/layout/<layout1>.xml
   <parent_theme_dir>/<Namespace>_<Module>/layout/<layout2>.xml

Copy that file and place it in the following location and then edit it:

<theme_dir>/
├── <Namespace_Module>/
│   ├── layout/
│   │   ├── override/
│   │   │   ├── theme/
│   │   │   │	├── <Parent_Vendor>/
│   │   │   │	│	├── <parent_theme>/
│   │   │   │	│	│	├── <layout1>.xml
│   │   │   │	│	│	├── <layout2>.xml

For example: app/design/frontend/Magento/luma/Magento_Catalog/view/frontend/layout/catalog_product_view.xml will be override by <theme_dir>/Magento_Catalog/layout/override/theme/Magento/luma/catalog_product_view.xml

While the layout override mechanism makes it easier for you when the amount of customization is overwhelming, you’re only up to making changes that don’t involve logic. since other modules can push content by block name or display them by alias, so you should not change block name and alias. Also don’t remove blocks from layout if not really sure.

Now, you can perform layout file override in your theme. We will continue to learn together about Magento layout in the next posts. Contact us if you face any problems during the installation process.

You can download the demo code for this entire series from GitHub