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.
Contents
1. Check again your controller action model:
/app/code/MagentoSharing/Example/Controller/Index/Index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
namespace MagentoSharingExampleControllerIndex; class Index extends MagentoFrameworkAppActionAction { /** * Execute action */ public function execute() { $resultPage = $this->resultFactory->create(MagentoFrameworkControllerResultFactory::TYPE_PAGE); return $resultPage; } /** * Action constructor * * @param MagentoFrameworkAppActionContext $context */ public function __construct( MagentoFrameworkAppActionContext $context ) { parent::__construct($context); } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" layout="1column" > <head> <title>MagentoSharing Example Index page</title> </head> <body> <referenceContainer name="content"> <block class="MagentoSharingExampleBlockIndexIndex" name="index" template="index/index.phtml" cacheable="false"> </block> </referenceContainer> </body> </page> |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php namespace MagentoSharingExampleBlockIndex; class Index extends MagentoFrameworkViewElementTemplate { public function __construct( MagentoFrameworkViewElementTemplateContext $context, array $data = array() ) { parent::__construct($context, $data); } } |
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.
1 2 3 |
<?php echo "This is template file for action example_index_index"; ?> |
Finally, you can visit http://yourdomain/example/index/index to view the result.
You can download the package of this tutorial here
Thank you for reading. If you have any problems, please contact us.