How to create a block in Magento 2?

by darrion.kuhn , in category: PHP CMS , 9 months ago

How to create a block in Magento 2?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 3 months ago

@darrion.kuhn 

To create a block in Magento 2, follow these steps:

  1. Create a new module by running the following command:
1
php bin/magento setup:module:create --name=Vendor_ModuleName --description="Module Description" --type=magento2-module


Replace "Vendor" with your vendor name and "ModuleName" with the desired name for your module.

  1. Create a block directory under app/code/Vendor/ModuleName/Block.
  2. Create a new PHP class for your block in the block directory. The class should extend MagentoFrameworkViewElementTemplate and implement the MagentoFrameworkViewElementBlockInterface interface.


Here is an example of a simple block class:

1
2
3
4
5
6
7
8
<?php
namespace VendorModuleNameBlock;

use MagentoFrameworkViewElementTemplate;

class MyBlock extends Template implements MagentoFrameworkViewElementBlockInterface
{
}


  1. Define the block in your module's etc/frontend/di.xml file:
1
2
3
4
5
6
7
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="VendorModuleNameBlockMyBlock">
        <arguments>
            <argument name="template" xsi:type="string">Vendor_ModuleName::myblock.phtml</argument>
        </arguments>
    </type>
</config>


  1. Create a template file for your block in the app/code/Vendor/ModuleName/view/frontend/templates directory. The name of the file should match the template argument that you defined in the di.xml file.
  2. To display the block in a page, you can use the getChildHtml method in the layout XML file for the page. For example:
1
2
3
4
5
<block class="VendorModuleNameBlockMyBlock" name="my_block" template="Vendor_ModuleName::myblock.phtml">
    <arguments>
        <argument name="some_argument" xsi:type="string">Some value</argument>
    </arguments>
</block>


Then, in your page template file, you can use the getChildHtml method to render the block:

1
<?php echo $this->getChildHtml('my_block'); ?>


  1. Flush the cache and test your block by visiting a page that uses the block.


I hope this helps! Let me know if you have any questions.