Skip to main content

How to change block's template with alias in Magento2 extension

How to change block's template with alias in Magento2 extension

as we know that some blocks does have alias without name in the xml files, so here we will see how we can change the template for a block with alias instead of name

I will put here an example on how to do it , this was tested in Magento 2.3.4

 

in the parent module we have this XML 

 

 <referenceBlock name="content">
        <block class="Magento\Catalog\Block\Product\View\Options" name="product.info.options" as="product_options" template="{Vendor}_{Module}::product/view/options.phtml">
            <block class="Magento\Catalog\Block\Product\View\Options\Type\DefaultType" as="default" template="product/view/options/type/default.phtml"/>
            <block class="Magento\Catalog\Block\Product\View\Options\Type\Text" as="text" template="{Vendor}_{Module}::product/view/options/type/text.phtml"/>
            <block class="Magento\Catalog\Block\Product\View\Options\Type\File" as="file" template="product/view/options/type/file.phtml"/>
            <block class="{Vendor}\{Module}\Block\Product\View\Options\Type\Select" as="select" template="{Vendor}_{Module}::product/view/options/type/select.phtml"/>
            <block class="Magento\Catalog\Block\Product\View\Options\Type\Date" as="date" template="product/view/options/type/date.phtml"/>
        </block>
        <block class="Magento\Framework\View\Element\Html\Calendar" name="html_calendar" as="html_calendar" template="Magento_Theme::js/calendar.phtml"/>
    </referenceBlock>

 

 

in our module we can override select block like this 

 <referenceBlock name="product.info.options">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">{Vendor1}_{Module1}::product/view/options.phtml</argument>
            </action>
            <referenceBlock name="select">
                <action method="setTemplate">
                    <argument name="template" xsi:type="string">{Vendor1}_{Module1}::product/view/options/type/select.phtml</argument>
                </action>
            </referenceBlock>
        </referenceBlock>

 

for some reason this way will not work as expected , so we can try this one 

<referenceBlock name="product.info.options">
<block class="{Vendor}\{Module}\Block\Product\View\Options\Type\Select" name="custom_renderer" template="{Vendor}_{Module}::/product/view/options/type/select.phtml"/>

<action method="setChild">
    <argument name="alias" xsi:type="string">select</argument>
    <argument name="block" xsi:type="string">custom_renderer</argument>
</action>
</referenceBlock>

 

 

in this way we override two blocks in the same xml file, hope this will help you 

Tags