This rather trivial requirement turns out be quite a pain for us in recent days, as we couldn't find a satisfying existing solution, yet.

The Task

We are trying to replace certain blocks with a custom template accompanied with a custom block class. Our extension has a system configuration with a couple of boolean inputs (Yes/No), if certain predefined custom blocks should be used. Each custom block replaces one or more default blocks.

If the Merchant selects "No", nothing should happen to these default blocks.


The search box in the container header-wrapper in the Luma theme has a block named top.search. We wand to replace this block with the my-search.phtml template and the MySearch block class, which inherits from the default search block class. In this case \Magento\Framework\View\Element\Template.

Current solutions

A) Using deprecated <action>-Tag with ifconfig-Attribute

My most favorable way was using layout xml files with basic layout definitions to fix our problem. We altered the layout as follows:

<referenceBlock name="top.search" class="Test\MyApp\Block\MySearch">
    <action ifconfig="myapp/components/searchbox" method="setTemplate">
        <argument name="template" xsi:type="string">Test_MyApp::my-search.phtml</argument>

Disadvantage: Magento2 documentation discourages from using <action>-Tag. If the search box feature is not used, it still overwrites the default block class.

B) Event-based block exchange using ObserverInterface

Disadvantage: It seems a bit hacky to me to use the event system in Magento2 to replace blocks on a certain condition. I get the feeling that this might also impact the performance, if a lot of blocks need to be replaced.

C) Insert a new and invisible block on every page that replaces default blocks on demand

// pseudocode
$layout = $this->getLayout();
$block = $layout->getBlock('top.search');
if ($block) {
  // todo only unset on condition

  $newBlock = $layout->createBlock('Test\MyApp\Block\MySearch', 'top.search', []);
  $layout->setBlock('top.search', $newBlock);

Disadvantage: Possible (unverified) performance and caching issues in the future. Similar to solution B.

The last solution (C) resembles our current pick. However, we are looking for a satisfying solution that works without using any PHP and is written in the Magento2 layout definition (XML). Any ideas?

  • Did you find a solution on this or just go with answer c)? – Dominic Xigen May 28 '19 at 20:55
  • No, we kept using this method. – Riccardo Baral May 29 '19 at 21:27

You can create a plugin for getTemplate() method for the desired block.

  • 1
    explain please with some code – Waqar Ali Dec 6 '19 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.