Magento 2 is one of the most popular e-commerce platforms, and it’s probably the most difficult to use for developers. One of the things you will use a lot while developing in Magento 2 is the XML layouts, which can be confusing in the beginning.
I will include some quick tips you might need in developing and modifying existing layouts.
Move Elements
If you want to move a block or container from one place to another in a page, you can use the following:
<move element="element.to.move" destination="new.parent" />
Here, we have the element
attribute which should be the name of the block or container you want to move, and the destination
attribute which should be the name of the block or container you want to move the element to.
You can also use before
or after
attributes to specify where the element should go inside the parent like this:<move element="element.to.move" destination="new.parent" after="new.sibling" />
where new.sibling
is another child in new.parent
Remove Element
To remove a block from a page, use the following:
<referenceBlock name="element.to.remove" remove="true" />
You can also do the same for containers:
<referenceContainer name="element.to.remove" remove="true" />
Note: When Magento applies layout changes, move
rules are applied before remove
. This means if you move an element to a parent, and remove then the parent, the element you moved into it will be removed as well.
Change a Block’s Template
To change a block’s template, you can do the following:
<referenceBlock name="block.to.change">
<action method="setTemplate">
<argument name="template" xsi:type="string">VENDOR_MODULE::path/to/template</argument>
</action>
</referenceBlock>
Where VENDOR_MODULE::path/to/template
should be the path to the new template you want to use for the block.
Change Block’s Visibility Based on Configuration
If you want a block to be visible based on configuration’s value that is set by the admin, you can do it this way:
<block class="..." name="..." ifconfig="my/yesno/field">
Where my/yesno/field
can be any path to a field in the system settings.
Remove CSS or JS files
To remove a css, javascript or any static file present in <head>
, use the following:
<head>
<remove src="src/to/file" />
</head>
Set Attributes of Body
To set attributes of the body of a page, like class, use the following:
<body>
<attribute name="class" value="class-name"/>
</body>
You can also set style
, class
and other attributes.
Conclusion
Those were just some quick tips you will probably use a lot if you’re developing a store with Magento 2. You can read more about this, as well as other helpful information, see here.