mrzaizai2233 / magento2-dev-log

0 stars 0 forks source link

How to change template Block and cacheable block using layout.xml #4

Open mrzaizai2233 opened 6 years ago

mrzaizai2233 commented 6 years ago

Using layout xml files like:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance dc" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
    </head>
    <referenceBlock name="product.info.options.select">
        <action method="setTemplate">
            <argument name="template" xsi:type="string">Absoft_WallCatalog::product/view/options/type/select.phtml</argument>
        </action>
    </referenceBlock>
    <referenceBlock name="product.info.addtocart.additional">
        <action method="setTemplate">
            <argument name="template" xsi:type="string">Absoft_WallCatalog::product/view/addtocart.phtml</argument>
        </action>
        <block class="Magento\Framework\View\Element\Text" cacheable="false" />
    </referenceBlock>
</page>

This solution requires finding all instances where the blok is used and create as many xml files as handles in which it is used. If the block is used very often or you want to make sure each new usage will not require adding this kind of configuration you can do it using plugin.

Plugin usage. Declare your plugin either in etc/di.xml or etc/frontend/di.xml

<type name="Other\Module\Block">
    <plugin name="very-unique-name" type="My\Module\Plugin\Block" />
</type>

And then create a class My\Module\Plugin\Block with content like

namespace My\Module\Plugin;

class Block
{
    public function beforeToHtml(\Other\Module\Block $block)
    {
        $block->setTemplate('My_Module::path/to/my/file.phtml');
    }
}