Create layout in Magento 2

Create layout in Magento 2- In part 1, we already created a simple Magento 2 module with a controller. You can view the tutorial here and download the package.
Next, we’re going to create layout for this controller.

Let’s begin.

1. Check again your controller action model:

/app/code/MagentoSharing/Example/Controller/Index/Index.php

2. In Magento 2, every action has its own layout file.

The action url is http://yourdomain/example/index/index ( or http://yourdomain/example ) so the layout file’s name should be example_index_index.xml
Let’s create a file /app/code/MagentoSharing/Example/view/frontend/layout/example_index_index.xml with content:

3. We also need create a block and a template file to render the layout.

Create a block: /app/code/MagentoSharing/Example/Block/Index/Index.php with content:

4. Create a template file

/app/code/MagentoSharing/Example/view/frontend/templates/index/index.phtml
Its content is what you want to display in frontend.

Finally, you can visit http://yourdomain/example/index/index to view the result.

Create layout for controller magento2

You can download the package of this tutorial here

Thank you for reading. If you have any problems, please contact us.

 

Leave a Reply

Your email address will not be published.