Magento – Adding block into an existing template

blocksmagento2xml

I'm trying to add some content of my block into the sales/order/history part.

I have this:

<?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">
    <body>
        <referenceBlock name="sales.order.history">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">My_Module::history.phtml</argument>
            </action>
        </referenceBlock>
    </body>
</page>

My_Module::history.phtml is adding some text just for the moment, but I want to add content that is on my block. How can I do that ?

Best Answer

The <action> node has been deprecated for a while now, you should stop using it right away. In fact, in Magento 2.2.4 (maybe even earlier) the node doesn't work anymore. With that being said, here are two different ways to accomplish your goal.

<?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">
    <body>
        <referenceBlock name="sales.order.history" template="My_Module::history.phtml" />
    </body>
</page>

OR

<?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">
    <body>
        <referenceBlock name="sales.order.history">
            <arguments>
                <argument name="template" xsi:type="string">My_Module::history.phtml</argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

To add content into your block, you can add additional arguments into the layout xml file. You can also refer to your block by name inside of a plugin. This is the best answer I can give without further clarification to your question.


Update after getting clarification of question. Here is how a child block should be added.

<?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">
    <body>
        <referenceBlock name="sales.order.history" template="My_Module::history.phtml">
            <arguments>
                <argument name="template" xsi:type="string">My_Module::history.phtml</argument>
            </arguments>
            <block class="Class\Of\My\Block" name="some.block.name" template="My_Module::some/template.phtml" />
        </referenceBlock>
    </body>
</page>

Inside of the file My_Module::history.phtml, you will need to have add one of these lines:

#this will render ALL child blocks in the same place
<?php echo $block->getChildHtml(); ?>

OR

#this will render only the specific child block you added
<?php echo $block->getChildHtml('some.block.name'); ?>