Remove Block Programmatically in Magento2

Viewed 5067

We are able to remove block in Magento1 with unsetBlock() method, but in Magento2 it is not working. So, please help how can remove block in Magento2 programmatically ?

4 Answers

Ideally there are different ways to do this. The best way of doing it is using a layout file.

1) If you have build a module you can create a layout which is an xml file in app/code/Namespace/Your_Module/view/frontend/layout/frontname_controllername_controlleraction.xml and add the below code

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceBlock name="block_name" remove="true" />
</page>

2) If you have not created a custom module of your's you can simply write a custom xml in app/design/frontend/Custom_Theme/Theme_name/Module_Name/layout and add the below code.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceBlock name="block_name" remove="true" />
</page>
Related