Day 3: How to create block and Template on a Page
Welcome to Day 3 of the Magento Advent Calendar. Today we’ll create a simple Magento 2 Block with a template, and render dynamic data on a page — something you’ll use in almost every real Magento project. Let’s jump right into the code.
Create a Block Class
A Magento Block is simply a PHP class that provides data to a template.
Create a new folder Block and inside it, file Info.php:
<?php
declare(strict_types=1);
namespace MageMastery\Module\Block;
use Magento\Framework\View\Element\Template;
class Info extends Template
{
public function getMessage(): string
{
return "Hello from MageMastery Advent Day 4!";
}
public function getCurrentTimestamp(): string
{
return date('Y-m-d H:i:s');
}
}
We extend Template, and expose a simple method getMessage() that returns a string.
Now let’s render it in the frontend.
Create the Template File
The view/frontend/templates/info.phtml file:
<?php
/** @var \MageMastery\Module\Block\Info $block */
?>
<div class="magemastery-advent">
<h1><?= $block->getMessage(); ?></h1>
<p>Current timestamp: <?= $block->getCurrentTimestamp(); ?></p>
</div>
The $block here is our Block instance, so the template can call any public method from the Block.
Add Layout XML
The view/frontend/layout/custom_example_index.xml file:
<?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="columns">
<block class="MageMastery\Module\Block\Info"
name="magemastery.advent.info"
template="MageMastery_Module::info.phtml" />
</referenceContainer>
</body>
</page>
This layout file tells Magento to render our Block inside the content container on the custom/example/index action.
If you missed Day 2 — that’s where we created the custom route and controller.
Now open the page:
/custom/example/index
And you should see “Hello from Advent Day 3!”.
That’s it for Day 3!
You now know how to create a Block, attach a template, and render data in Magento 2 something you’ll do in every project. Tomorrow in Day 4 we’ll build on top of this and make the page even more dynamic.
Don’t forget to subscribe, and I’ll see you tomorrow.
Also, please check the Day 3 video I’ve prepared as part of the Magento Advent Calendar.
