Today we will learn how can we call a block or show a template file on homepage with a layout file.
The main question here is what is the layout file for homepage and the answer is cms_index_index.xml.
So first create a cms_index_index.xml file under Webkul/HelloWorld/view/frontend/layout/ folder
<?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"> <body> <referenceContainer name="content"> <block class="Webkul\HelloWorld\Block\HomePage" name="wk_helloworld_homepage_block" template="Webkul_HelloWorld::homepage.phtml"/> </referenceContainer> </body> </page>
Then create a HomePage.php under Webkul/HelloWorld/Block/ folder
<?php namespace Webkul\HelloWorld\Block; class HomePage extends \Magento\Framework\View\Element\Template { public function getMessage() { $msg = "Hello World"; return $msg; } }
After that create a homepage.phtml file under Webkul/HelloWorld/view/frontend/templates/ folder
<h1><?php echo $block->getMessage();?></h1> <p>Some content here</p>
Home Page view

There is one more way to show a block on homepage, you can check it here Call Phtml file on CMS Page – Magento2.
Happy coding 🙂 Feel free to comment if you have any issue.
Be the first to comment.