2Hats . 2 minutes
September 22, 2016

Beginners guide to customize layout in Magento2

It’s difficult for a beginner to go into Magento developer docs and understand the whole concept of layout handling with xml files. The layout files are .xml files located in the layouts folder of the theme/component.

The layout file defines the position, template file, arguments, html attributes, etc. for each block. A template file (with .phtml extension) is the HTML part that is loaded by how the XML is configured.

Magento has this feature to turn on template path hints which is an absolute lifesaver for beginners who try to figure out which template is used for a particular section. It also gives the block class name used. Below is an image of Magento showing the path hints.

template-hints

 

Here, we can see that the cart image is displayed from the minicart.phtml in the checkout module.

Customizing Layouts

You can add, modify, or remove a block and its sub-elements. Firstly, find the name of the parent element/ block you want to modify.

  1. To update a block use the <referenceBlock>, which means which block it refers to.
    Example: to pass an image to the logo block.
    Example 2: to add a new block to the top.links section
  2. The <remove> attribute is optional and its default value is false. This removes the block if set to true.
    Example:
  3. The <display> attribute is optional and its default value is true. This hides the block if set to false.
    Example:
  4. The <move> Sets the declared block or container element as a child of another element in the specified order.
  5. <before> and <after> attributes of <block>: Used to position the block before/after an element under the same parent. The element name or alias name is specified in the value. Use dash (-) to position the block before/after all other elements of its level of nesting.  These attributes are optional.
    top

     

    For example in the above screenshot if you want to move the search box to the top “header.links” section, add this line in your custom layout file.
    Then the result will be as below.

    top-moved

Hope this gives a basic idea of layout handling for beginners. Drop us any questions you may have.

blog
Greetings! I'm Aneesh Sreedharan, CEO of 2Hats Logic Solutions. At 2Hats Logic Solutions, we are dedicated to providing technical expertise and resolving your concerns in the world of technology. Our blog page serves as a resource where we share insights and experiences, offering valuable perspectives on your queries.
Aneesh ceo
Aneesh Sreedharan
Founder & CEO, 2Hats Logic Solutions
Subscribe to our Newsletter
Aneesh ceo

    Stay In The Loop!

    Subscribe to our newsletter and learn about the latest digital trends.