Magento 2 – How to Call Custom PHTML File in CMS Block/Page

layoutmagento2phtmlview

There may be situation when you are developing a Project, you may need to call a custome phtml file in

  • another phtml file
  • cms page
  • cms block (static block)
  • xml layout

How to do it ?

Best Answer

For the Example purpose we use below custom file, we want to include

app/design/frontend/<vendor>/<theme>/Magento_Theme/templates/extra/test-view.phtml

Calling in phtml file

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

or alternatively

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

Calling in CMS page and block

Calling in CMS page and block is exactly same

{{block class="Magento\Framework\View\Element\Template" name="test_view" template="Magento_Theme::extra/test-view.phtml"}}

Calling in XML layout

<block class="Magento\Framework\View\Element\Template" name="test_view" template="Magento_Theme::extra/test-view.phtml"/>