Magento2 Call phtml File from Another phtml File – Step-by-Step Guide

layoutmagento2template

I want to add new phtml file to existed phtml file. It is working fine, but I want to know reference block and class names.

My code in layout file

    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>       
   <block class="Magento\Framework\View\Element\Template" template="Magento_Test::test.phtml"/>
</body>

In layout file, Here I need to add reference block/container or no need?

Existed code phtml file is

<?php echo $this->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setTemplate("Magento_Test::test.phtml")->toHtml();?>

Best Answer

Layout Method

If you want to added another phtml file using the layout, then you need to give name to your block like this one :

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>       
   <block class="Magento\Framework\View\Element\Template" name="mytestblock" as="mytestblock" template="Magento_Test::test.phtml"/>
</body>

then you can use like refrenceBlock="mytestblock" to call another phtml using layout.

Direct Method

You want to call phtml into another phtml then you can use this code.

<?php echo $this->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setTemplate("Magento_Test::newtest.phtml")->toHtml();?>