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.
Contents
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.
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!
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!
Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…
MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…
In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…
Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…
The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…
Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…
View Comments
I get Undefined type 'app\code\Vendor\Extension\Observer\ModifyBlock'.
Also your xml is corrupted, you are missing the closing config tag.
Please Confirm you created that block, or if you need to replace those block with your real block file