+92-301-1000201 [email protected]
31 views

In the previous tutorial of Magento 2 extension development, we learned how to display a message on the web browser using the action method. There was no header and footer displayed in the output.

For that, we need to create a template.

This tutorial explains how to create a block and template file in Magento 2.

When we want to display content using an action method, we need to create a block and template file.

Block file has functions that we use in a template file. Moreover, the template also includes the content that has code related to HTML and PHP.

The XML file for layout demonstrates which block and which template file will be called.

Another important thing to keep that in mind is that you have to create a layout file based on the action that you have developed.

We will continue with the same example that we discussed in the previous tutorial. Therefore, we have to create a file having extension_index_index.xml name. You may have a question why the XML file is created with a name of extension_index_index.xml. It is because the action that we developed was extension/index/index.

Method to Create Block Template in Magento 2

1. Update Controller File:

Earlier, the message was just printed. Now, what we are doing is to print a message with a page.

To do this, we have to update the code in a file app/code/Meetanshi/Extension/Controller/Index/Index.php

2. Create a Block File:

For creating a block file, give the name Form.php and create this file in a given path.

app\code\Meetanshi\Extension\Block\Form.php

3. Create a Template File:

Creating a template file is extremely simple.

Save form.phtml with the given code below and use the path for creating the file.

app\code\Meetanshi\Extension\view\frontend\templates\form.phtml

4. Create a Layout File:

The last and the final file that you need to create a block template is the layout file.

Make sure, the name of your layout file has to be extension_index_index.xml.

In the given path, use the code and save the file.

app\code\Meetanshi\Extension\view\frontend\layout\extension_index_index.xml

You can check which block file and template file are being called.

Here is how the output looks on the frontend

Here is how the output looks on the frontend. As you can see in the below image, the output now shows header and footer.

Also, Luma is a default theme of Magento 2. Therefore, you will see Luma theme for the output of your extension.

That’s it.

If you have questions, feel free to ask in the Comment section below.

Do share this post to beginner and passionate who wants to learn Magento extension development.

Thank you.