How to create a custom block in Magento 2

1. Add a new PHP class block.

Create the file in the following location:

app/code/<VendorName>/<ModuleName>/Block/<fileName>.php

and add the following code to it:

<?php

namespace VendorName\ModuleName\Block;

class <filename> extends \Magento\Framework\View\Element\Template
{
  

}

\Magento\Framework\View\Element\Template — a class from which you inherit your own block that interacts with the template.

2. Add a template file (template .phtml file)

Create this file:

app/code/<VendorName>/<ModuleName>/view/frontend/templates/<file-name>.phtml

3. Combine the PHP class block and the template file in a layout file.

Create this file:

app/code/<VendorName>/<ModuleName>/view/frontend/layout/<rute_id>_<controller_name>_<action_name>.xml

and add the following code to it:

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
     <body>
         <referenceContainer name="content">
             <block class="VendorName\ModuleName\Block\<filename>" name="file.name.name" template="VendorName_ModuleName::<file-name>.phtml" />
         </referenceContainer>
     </body>
</page>

<rute_id>_<controller_name>_<action_name> — the layout file name, should only be in lower case and contain the router id, controller and action names.

layout — an attribute that defines the type of page layout. The following types are available by default: 1column, 2columns-left, 2columns-right, 3columns, empty. Experiment with them — set different types of layouts and compare them.
content — the name of the container where the block will be placed.

Leave a comment

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