Include template into another template in Magento2

In this topic we describes the way to include template file into another template. Subscribe to Bethos for all the Magento2 problems and customizations.

Using getTemplateFile method:

If you need to include phtml template file into another phtml, Magento provides a inbuilt function called getTemplateFile.

For example:

Here is my first template app/code/Bnethos/Example/view/frontend/templates/mainTemplate.phtml

In the above example, inside the mainTemplate.phtml we included multiple template using $block->getTemplateFile(“Path”);

You may wonder what getTemplateFile doing here. If you check the vendor magento path vendor/magento/framework/View/Element/Template.php. You can find the below function, this function return the path of the template file which we are passing as arguments, then we used include statement to include the file into the phtml.

Using setTemplate method.

If you want to include your custom block functions in the including template. you can use this method.
For example:

The above example, wrapes the custom block with the included template which we are passing inside setTemplate() function and return the data as HTML values.

If you need more help regarding this post, feel free to ask in the Comments section below.

I would be happy to solve your queries.

Leave a Comment