8

I have found multiple threads related to calling helper function in .phtml.

But I have a case where I need to call phtml file in helper and return HTML.

I have used this code:

//Where $this->_resultPageFactory is the object of \Magento\Framework\View\Result\PageFactory
$resultPage = $this->_resultPageFactory->create();
$html = $resultPage->getLayout()
            ->createBlock("Vendor\Module\Block\Index")
            ->setTemplate("Vendor_Module::index.phtml")
            ->toHtml();
return $html;

It is working fine, but the problem is, it is effecting other stuff like Product title, Media gallery etc (it is changed after using above code)

So, how can I call .pthml from helper?

2 Answers 2

8

I have figured out the solution. Copied from gift-card module (Enterprise)

For variables in constructor

protected $_layout;

public function __construct(
    ...
    \Magento\Framework\View\LayoutInterface $layout
    ...
) {
    $this->_layout = $layout;
    ...
}

Now in any of the function where you want to call phtml, use this:

$block = $this->_layout->createBlock(\Vendor\Module\Block\Index::class);
$block->setTemplate("Vendor_Module::index.phtml");
return $block;
2
  • hello @Shoaib Thnk you for your effort but in my case it is not working I need to get phtml file data using helper can you please look in to this code. $block = $this->_layout->createBlock(\Vendor\Module\Block\Index::class); $block->setTemplate("Vendor_Module::index.phtml")->toHtml(); Commented Feb 4, 2020 at 5:52
  • Please share your constructor code Commented Feb 4, 2020 at 5:55
3

You can use this:

$block = $this->_layout->createBlock(\Vendor\Module\Block\Index::class);
$block->setTemplate("Vendor_Module::index.phtml");
return $block;

Where $this->_layout is the instance of \Magento\Framework\View\LayoutInterface

1
  • My answer is almost same, but +1 for your efforts Commented Dec 25, 2019 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.