Back to Top

How to show a block content on homepage with layout file in Magento 2

Updated 27 February 2024

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

Searching for an experienced
Magento 2 Company ?
Find out More
<h1><?php echo $block->getMessage();?></h1>
<p>Some content here</p>

Home Page view

cms page image

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.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home