This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Peak Performance.

Limitless Scalability.

  • 0

    Days

  • 0

    Hours

  • 0

    Mins

  • 0

    Sec

Off For 4 months
+40 free Migrations

Secure Any CMS With Ease with Our Malware Protection Add-On! LEARN MORE→

Magento 2 Create Custom Block, Layouts and Templates – Step by Step

Updated on July 14, 2023

6 Min Read
Magento 2 Layouts, Blocks, and Templates - Banner

An ecommerce store’s layout and structure are essential for easy navigation, intuitiveness, and user-friendliness.

When it comes to Magento 2, layouts and templates build the blocks of a theme. Layouts are the XML files that specify the overall structure of a page, like a header’s position, side columns, footer, etc. Templates are pieces of code in PHTML (PHP) files that add features and contents you see on the front page.

Magento 2 Module Structure

Previously, we learned how to create Magento 2 module structure and how to create a magento custom module. In this guide, I intended to focus on working around Magento 2 blocks, layouts, and templates. To understand how Magento 2 layouts, blocks, and templates work, let’s try adding a sample text on the Magento 2 homepage. We will start the implementation of our ViewModel and Controller.

Step 1: Create Controller

The controller is an integral part of the Magento module for handling the requests rendering on the page. Create a new controller to add a new page in Magento 2. In Magento 2, a controller is a file located at a specific place that responds to a particular route.

Controllers files in Magento 2 will be located at:
app/code/<VendorName>/<ModuleName>/Controller/<ControllerName>/<ActionName>.php

Create Custom Controller

Firstly, create a controller to call the layout .xml file:
app/code/Cloudways/Mymodule/Controller/Index/Welcome.php

Add the following code:

<?php

namespace Cloudways\Mymodule\Controller\Index;




class Welcome extends \Magento\Framework\App\Action\Action

{

protected $_pageFactory;

public function __construct(

\Magento\Framework\App\Action\Context $context,

\Magento\Framework\View\Result\PageFactory $pageFactory)

{

$this->_pageFactory = $pageFactory;

return parent::__construct($context);

}




public function execute()

{

return $this->_pageFactory->create();

}

}

To render the content on the view page, we have to use the execute method. I.e

return $this->_pageFactory->create();

We will use Page Factory to create a new page PageFactory, which is an instance of: \Magento\Framework\View\Result\PageFactory. The returned results mean that your action will return HTML.

Looking for a Fast and Hassle Free Magento Hosting Experience?

Cloudways offers a fast, cost-effective, and easy-to-manage Magento 2 hosting solution that you can deploy on top 5 Infrastructures that includes AWS, Google Cloud, Digital Ocean, Linode, and Vultr.

Step 2: Create Layout File

The layout creates a link between the Block class & the template to manage and describes the page’s structure. The layout file is an xml file containing multiple layout instructions located at {module_root}/view/{area}/layout/ folder. The Area path can be front-end or adminhtml, which defines where the layout will be applied. The layout structure for the front-end application is defined under view/frontend/layout/.

You can customize a layout in two ways:

  • Creating a new Layout
  • Altering the Layout files

To make changes to every page of your website, modify the default.xml file. For example, default.xml will be located in app/code/Vendor/Module/view/frontend/layout/default.xml to load the changes on all pages.

To add a layout for the specific page in your module create the layout file with name as format: {router_id}_{controller_name}_{action_name}.xml.

In the previous article on the magento custom module, we learned about creating the router_id in the routes.xml file. If you want to check you can look into it.

Experience the Cloudways Magento 2 Demo Store – No tech skills needed!

Experience a fully functional Magento 2 store built on top of renowned Cloudways hosting to deliver the fastest speeds.

Create a New Layout

We will create a layout handle file for this module:

File: app/code/Cloudways/Mymodule/view/frontend/layout/myroute_index_welcome.xml

Add the following code:

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    <referenceContainer name="content">

        <block class="Cloudways\Mymodule\Block\Display" name="welcome_display" template="Cloudways_Mymodule::saywelcome.phtml" />

    </referenceContainer>

</page>

Here, we must define three critical structures in the Magento layout: Blocks, Containers, and Templates. For documentation, you can check to follow the layout instructions.

In the above code, we must define three different structures of Layout: Block, container, and template. Let’s look into it.

Blocks are defined using the <block> element in the layout’s XML file as I created the Cloudways\Mymodule\Block\Display file.

Now, let’s see Magneto block element parameters in detail:

class – It is a required attribute that defines a block’s class for the template file.

name – It is also a required attribute and is used to identify a Magento block as a reference.

template – It is used to define the link of a PHTML file where we write our HTML or PHP code.

Step 3: Create Block

Details: Magento block is a modular content unit that can be placed anywhere on the page. Blocks in Magento are referred to as static blocks or CMS blocks. They help display fixed information such as text, images, and embedded videos, as well as dynamic information from a widget originating through the database.

The Block file contains all the functional logic used in the view template and the content related to HTML and PHP. Let’s create the custom Block class by following the steps below:

Create a file:

app/code/Cloudways/Mymodule/Block/Display.php

Contents would be:

<?php

namespace Cloudways\Mymodule\Block;

class Display extends \Magento\Framework\View\Element\Template

{

public function __construct(\Magento\Framework\View\Element\Template\Context $context)

{

parent::__construct($context);

}




public function sayWelcome()

{

return __('Welcome!');

}

}

Step 4: Create Template File

Details: Templates are part of the view layer of the page. Magento 2 templates are initiated in layout files and define how the content is rendered on the page. However, I recommend consulting a Magento developer if you want to redesign your application or customize the templates.

Create a template file named as sayhello.phtml

app/code/Mageplaza/HelloWorld/view/frontend/templates/saywelcome.phtml

Insert the following code:

<?php




/**

 * @var \Cloudways\Mymodule\Block\Display $block

 */




echo $block->sayWelcome();

In the template file, we can use the variable $block for the block object. As you see, we call the method sayWelcome() in Block.

Optimize Magento Speed Like a Pro

Subscribe now and get a free ebook to your inbox.

Thank You

Your Ebook is on it’s Way to Your Inbox.

Step 5: Flush Magento Cache

Use the below command to flush the Magento cache:

Php bin/magento c:f

Php bin/magento cache:flush

Step 6: Run a test

Open your browser and navigate to the following link:

http://your-magento-store.com/path/сontrollerName/actionName/

In our case:

https://magento-761105-2575467.cloudwaysapps.com/myroute/index/welcome

You will see the below page:

magento LUMA

How to Add New CMS Block in Magento 2 Admin

Follow the steps below to add a new CMS block in Magento 2 admin

  • On the Admin panel, click Content > Elements > Blocks.
  • Click on the Add New Block button in the upper-right corner and continue.
  • In the Block Title field, enter the name title of the new block.

magento block view

  • If you want to change the default-enabled status of the new block, set Enable Block to No.
  • Assign a Block Title for internal reference.
  • Assign a unique Identifier for the block.
    Use all lowercase characters with underscores instead of spaces.
  • Select each Store View where you want the block to be available.
  • Add content for the block using the displayed content toolset:
  • If the Page Builder is enabled, the content workspace will include the Page Builder tools.

magento block content

Once completed, click the Save arrow and choose Save & Close.

Final Words

This guide describes using Magento 2 layouts, blocks, and templates. Magento 2 offers an easy way of creating custom themes and front views, in addition to extending current layouts and overriding existing ones.

While working on backend or frontend development, loading issues can become a problem. This is why it is crucial to opt for an efficient Magento website hosting service that guarantees fast response times and loading speed.

Q1. What is Magento 2 Block?

Magento block is a modular unit of content that can be placed anywhere on the page. Blocks in Magento are referred to as static blocks or CMS blocks. They help to display fixed information such as text, images, and embedded video, as well as dynamic information from a widget that originates through the database.

Q2. What is the use of blocks in Magento 2?

Blocks are a foundational building unit for layouts in Magento. They are the link between a PHP block class containing the logic and a template that renders content.

Q3. What is a PHTML file in Magento?/strong>

PHTML is the root template for all storefront pages in the Magento 2 application. This file can be overridden in a theme just like any other template file but unlike root. PHTML contains the doctype specification and contributes to sections.

Q4. How do I get blocks in Magento 2?

Follow the steps below to get blocks in Magento 2:

  • Login to Magento 2
  • Navigate to Blocks
  • Click “Add New Block“, add the below information and save the configuration

Enable Block: Enable the block. Block Title: Name of the block to easily identify the purpose of creating the block.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Jyotishna Kumari

Jyotishina is the Magento Community Expert at Cloudways and has 4 years of experience in web development. She has worked on e-commerce sites since the turn of the millennium and was working with Magento before version 1 was released. She loves to travel and explore new ideas whenever she finds time. Get in touch with her at [email protected].

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

Peak Performance.

Limitless Scalability.

  • 0

    Days

  • 0

    Hours

  • 0

    Mins

  • 0

    Sec

Off For 4 months
+40 free Migrations

Claim Now