Magento2 Layout – Block/Element Order

layoutlayout-updatemagento2xml

A pretty basic question mainly because I'm still trying to wrap my head around Magento 2's templating system. But I'm just trying to switch the order of the mini-cart element and the search element in the header so that the search element is before the mini-cart element in the markup. For example, instead of

<div data-block="minicart" class="minicart-wrapper">...</div>
<div class="block block-search">...</div>

I want it to be:

<div class="block block-search">...</div>
<div data-block="minicart" class="minicart-wrapper">...</div>

Thanks!

Best Answer

This question has asked many times but no one have explained briefly so I have decided to answer what is the essential part to make move elements.

whenever you want move position of the element, first you need to find that particular element resides on which layout file?

For find appropriate layout file:

for example I could take search form and mini cart

enter image description here

Enable debug mode in Admin in order to find the template path, please follow the below instruction to enable template path hints. first login to admin then follow

Store -> configuration -> Advanced -> Developer -> Debug -> Enabled Template Path Hints for Storefront -> YES

after that flush the cache then load your page.you can able to see the template paths.

enter image description here

/var/www/html/magento2/vendor/magento/module-search/view/frontend/templates/form.mini.phtml use this template path you can find the layout location /var/www/html/magento2/vendor/magento/module-search/view/frontend/layout/default.xml

In that layout file you notice that form.mini.phtml resides on block name top.search under header-wrapper container. similarly you can find the all appropriate layout file

/var/www/html/magento2/vendor/magento/module-checkout/view/frontend/templates/cart/minicart.phtml resides on block name "minicart" under header-wrapper container

Move Elements:

below line is do the trick of move elements. you can add this line in your custom theme layout.

<move element="minicart" destination="header-wrapper" before="top.search" />

Your layout file should be like below

<magento-root>/app/design/frontend/<vendor-name>/<theme-name>/Magento_Theme/layout/default.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
    <move element="top.search" destination="header-wrapper" before="minicart" />
    </body>
</page>

after that clear cache of magento and browser then load your page it look like

enter image description here

for any clarification you need, feel free to mention in comment.

have good luck.

Related Topic