Magento 2 - How to call a custom phtml file in another phtml file, xml layout, static block and cms page?

51,358

Solution 1

For improving documentation/answer

Custom file path

app/design/frontend/{Package}/{theme}/Magento_Theme/templates/html/test.phtml

calling in xml layout file

<block class="Magento\Framework\View\Element\Template" name="test_file" template="Magento_Theme::html/test.phtml"/>

Calling in blocks and cms pages

{{block class="Magento\Framework\View\Element\Template" name="test_file" template="Magento_Theme::html/test.phtml"}}

Calling in any phtml file

<?php include ($block->getTemplateFile('Magento_Theme::html/test.phtml')) ?>

OR, as before

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

Solution 2

General convention is <VendorName_ModuleName>::relative/path/to/phtml/in/templates/

Examples:

Solution 3

Your custom file path

app/code/{vendor_name}/{module_name}/view/frontend/templates/custom.phtml

calling in phtml file into cms block and pages:-

{{block class="Magento\Framework\View\Element\Template" template="Vendor_Module::custom.phtml"}}

OR

{{block class="Vendor\Module\Block\your_file_name" template="Vendor_Module::custom.phtml"}}

calling in xml layout file:-

<block class="Magento\Framework\View\Element\Template" template="Vendor_Module::custom.phtml">

calling in another phtml file:-

<?php echo $this->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setTemplate("Vendor_Module::custom.phtml")->toHtml();?>
Share:
51,358
Milan Chandro
Author by

Milan Chandro

Big fan of LAMP, Magento, JavaScript Lover.

Updated on July 09, 2022

Comments

  • Milan Chandro
    Milan Chandro almost 2 years

    I am creating a magento 2 theme. I just want to know how can I add .phtml file in xml layout, static block, cms page or in another .phtml file. Thank You.