Magento 2 – Change Template of a Block Without Name

blocksmagento2template

I want to change to override a block's template with my custom template. But it does not have a "name", it only has a "as".
The one I want to override is:

<block class="Magento\Sales\Block\Adminhtml\Order\View\Items\Renderer\DefaultRenderer"
       as="default"
       template="order/view/items/renderer/default.phtml"/>

Best Answer

How to override a template having layout ALIAS.

This answer is a possible example, you can follow this to override ALIAS template.

I have created two example modules, Vendor_Module has layout with alias template, We are overriding this alias by Vendortwo_Moduletwo module.

Assume you know the steps to create module, i am not posting entire module creation.

Module 1

\app\code\Vendor\Module\etc\frontend\routes.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="standard">
        <route id="module" frontName="module">
            <module name="Vendor_Module" />
        </route>
    </router>
</config>

\app\code\Vendor\Module\view\frontend\layout\module_test_test.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
     <body>     
        <referenceContainer name="content">         
            <block class="Vendor\Module\Block\Test\Test" name="test_test" template="test/test.phtml">
                <block class="Vendor\Module\Block\Test\Test" as="testali" template="test/testali.phtml"/>
            </block>
        </referenceContainer>      
    </body>
</page>

Module 2

\app\code\Vendortwo\Moduletwo\etc\frontend\routes.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="standard">
        <route id="moduletwo" frontName="moduletwo">
            <module name="Vendortwo_Moduletwo" />
        </route>
    </router>
</config>

\app\code\Vendortwo\Moduletwo\view\frontend\layout\default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <referenceBlock name="test_test">
            <block class="Vendortwo\Moduletwo\Block\Two\Two" as="testali" template="two/twoalias.phtml"/>
        </referenceBlock>
</page>

After removing cache, i run http://localhost/magento210/module/test/test

The alias template is override by Vendortwo_Moduletwo two/twoalias.phtml

enter image description here