Magento 2: How to Call phtml File in Helper

How to Call phtml File in Helper in M2

Hello Magento Friends,

Hope all are doing well. Today I am going to explain Magento 2: How to Call phtml File in Helper. In case you missed out our previous blog, check it out here. Magento 2: How to Create/Add Custom Cache Type in Cache List.

Magento 2 E-commerce platform allows adding functionalities to your website. But changing the core files of Magento 2 is not a good practice. For this, the Magento helper class is used to override the core files. To add a phtml file from helper then the below code is useful. Let’s look at the steps to Call the phtml File in Helper in Magento 2.

Steps to Call phtml File in Helper in Magento 2:

Step 1: First you need to add Data.php in the following path:

app\code\Vendor\Extension\Helper

Then, add the below code

<?php

namespace Vendor\Extension\Helper;


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

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

    public function getPhtmlFile()
    {

        $layout = $this->layoutFactory->create();
        $blockOption = $layout->createBlock("Vendor\Extension\Block\Extension")->setTemplate("Vendor_Extension::extension.phtml");
        
       return $blockOption->toHtml();
    }
}

Step 2: Now you need to add the Extension.php file in the following path:

app\code\Vendor\Extension\Block

And add the below code

<?php
namespace Vendor\Extension\Block;

class Extension extends \Magento\Framework\View\Element\Template
{
    public function getDisplayText()
    {
        return "This is display text";
    }   
}

Step 3: After this now you need to add the extension.phtml in the following path:

app\code\Vendor\Extension\view\frontend\templates

And finally, add the below code:

<?php 
	echo $block->getDisplayText();
?>

That’s it!

Conclusion:

Hence, this way you can call phtml file in helper in Magento 2. While implementing the above code, if you come across any hardship, let me know in the comment section. Do share the article further and stay connected for more updates.

Happy Coding!

Previous Article

How to Change Copyright Notice in Magento 2

Next Article

How to Configure Security Scan in Magento 2

Write a Comment
  1. Thanks for tutorial. However i try to call the getPhtmlFile from model and got error critical Invalid template file

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨