Magento 2: How to get custom phtml file content and use it?

In this blog, we will learn about how to get block html and used in any page on front. We can do it many ways as per our need.

Let’s start to learn each way in details.

Call phtml file in other phtml file directly

When you have custom phtml in your custom theme and you want to use in other pthml file then you can do it by Magento default block class.

<?php 
	echo $this->getLayout()
			->createBlock("Magento\Framework\View\Element\Template")
			->setTemplate("Magento_Catalog::catalog/product/custom.phtml")
			->toHtml() ;
?>

Suppose, you have created custom module and you want to call module phtml in other phtml file than you can get it by:

<?php 
	echo $this->getLayout()
          ->createBlock('Mageclues\HelloWorld\Block\HelloWorld')
          ->setTemplate('Mageclues_HelloWorld::helloworld.phtml')
          ->toHtml();
?>

Call phtml file in CMS BLOCK and CMS PAGE

We provide two example for get phtml content in cms page and block, you can use it as per your need.

Example 1:

{{block class="Magento\Framework\View\Element\Template" template="Magento_Catalog::catalog/product/custom.phtml"}}

Example 2:

{{block class="Mageclues\HelloWorld\Block\HelloWorld" template="Mageclues_HelloWorld::helloworld.phtml"}}

Call phtml file in Helper class

With the help of helper class function, we can get phtml file content and then call helper function where you want to use it.

How to create custom helper in Magento 2

<?php
namespace MageClues\HelloWorld\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $_layoutFactory;

    public function __construct(\Magento\Framework\View\LayoutFactory $layoutFactory)
    {
        $this->_layoutFactory = $layoutFactory;
    }

    public function getHelloContent()
    {

        $layout = $this->_layoutFactory->create();
        $blockHtml = $layout->createBlock("MageClues\HelloWorld\Block\Hello")
						->setTemplate("Mageclues_HelloWorld::helloworld.phtml")
						->setData('area','frontend') // optional
						->setResponse($productId)  // optional
						->toHtml();
        
       return $blockHtml;
    }
}

After that you need to call helper function from phtml and wherever you want to use it. How to Call Helper Function in phtml in Magento 2

This also useful when you are working with AJAX and need to get block html response.

We hope this blog is helpful for you. if you have any question then please left comment.

Thank you):

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *