Site icon MageComp Blog

Magento 2: Append Block to Specific Container Dynamically

Append Block to Specific Container Dynamically in M2

Hello Magento Friends,

In today’s article, I will be explaining Magento 2: Append Block to Specific Container Dynamically. Let’s check out our previous blog, Magento 2: How to use Default Curl Class For API Call

Introduction:

Blocks are used to display information in the form of text, images, videos, or dynamic information in Magento 2. We can add or remove blocks as per the requirement. Sometimes you come across the need to add a block to a specific container dynamically in Magento 2. Let’s dive into the steps to append block to specific container dynamically in Magento 2. 

Steps to Append Block to Specific Container Dynamically in Magento 2:

Step 1: First you need to create events.xml in the following path

app\code\Vendor\Extension\etc\frontend

Now, add the below code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="core_layout_render_element">
    <observer name="load_custom_handler" instance="Vendor\Extension\Observer\Appendblock" />
</event>

Step 2: Now you need to add the Appendblock.php file in the following path

app\code\Vendor\Extension\Observer

And finally, add the below code

<?php
namespace app\code\Vendor\Extension\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class Appendblock implements ObserverInterface
{
  private static $_layoutSet = false;

  public function execute(Observer $observer)
  {
     // Run this only once
     if(ModifyBlock::$_layoutSet) { return; }
     Appendblock::$_layoutSet = true;
     $layout = $observer->getLayout();
     // Add a new block
     $layout->createBlock('Vendor\Extension\Block\Index\Index', 'custom-index-index');
     $layout->setChild('content', 'custom-index-index', 'custom-index-index');
     return;
  }
}

That’s it!

Conclusion:

Hopefully, everyone is able to append blocks to specific containers dynamically in Magento 2. In case you address the difficulty while performing the above steps, feel free to ask me in the comment section. Spread the article amongst your Magento friends to help them out with the solution. See you back soon, till then stay connected with us.

Happy Coding!

Exit mobile version