Magento 2 : Understand layout XML files

YouTube player

. What is a Layout XML File?

“A layout XML file in Magento is like a blueprint for your page. It defines the structure and content of a page using XML.”


2. Creating the Layout Directory

In our root module path we will create the file in this location

frontend/layout/kickstart_index_index.xml


3. Understanding the URL Anatomy

“Magento URLs have three parts: front name, controller name, and action name. For example, in the URL example.com/kickstart/index/index:

  • kickstart is the front name.
  • index is the controller name.
  • index is the action name.”

4. Naming Your Layout File

“Name your layout XML file using the URL parts. For the URL example.com/kickstart/index/index, the file name should be:

kickstart_index_index.xml


5. Creating the Layout XML File

“Let’s create the layout XML file with the correct structure.”

Steps:

  1. In your layout directory, create a new XML file named kickstart_index_index.xml.
  2. Add the following content to the file:
<referenceContainer name="content">

<block name="itcforu_kickstart_welcome" template="Itcforu_Kickstart::welcome.phtml"/>

</referenceContainer>

6. Explanation of the XML Content

“Let’s break down what we just added:

  • The <page> node is the root element.
  • Inside <body>, we have a <referenceContainer> node referring to the content container.
  • We add a node inside the container, specifying:
    • class attribute for the block class.
    • name attribute to uniquely identify the block.
    • template attribute to specify the template file.”

Summary:

“To recap:

  • Magento uses XML files to define page layouts.
  • We created a layout XML file and added a block to the content container.
  • We created a template file for the block.
  • We flushed the cache to apply changes.”

Activity:

“Now it’s your turn! Create a layout XML file and a template file for a custom URL, then refresh your Magento site to see the changes.”

I hope you found this video informative and helpful. If you did, please give it a like and share it with your colleagues