Call phtml File From Helper In Magento 2

Written by Mahesh Makwana

Aug 08, 2021

Call phtml File From Helper In Magento 2

We can call phtml file form many ways. Here we will show you how to call phtml file From Helper. Helper functions are accessible for all areas of Magento.

Add below code in Data.php at app/code/VendoreName/ModuleName/Helper

<?php

namespace VendoreName\ModuleName\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper
{
    protected $layoutFactory;

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

    public function getPHtmlFile()
    {
        $layout = $this->layoutFactory->create();
        $blockOption = $layout->createBlock("Your Block path")->setTemplate('VendoreName_ModuleName::YourphtmlfileName.phtml')
        return $blockOption->toHtml();
    }
}

Here block file and phtml file must be in same area. \Magento\Framework\View\Element\Template extends class are frontend class which phtml file path is app/code/VendoreName/ModuleName/view/frontend/templates and \Magento\Backend\Block\Template extends class are Adminhtml class which phtml file path is app/code/VendoreName/ModuleName/view/adminhtml/templates. We can call getPHtmlFile() function are call everywhere you want to call.

Note: If your phtml file does not use any block then you must pass the default class which is extended.

Frontend : Magento\Framework\View\Element\Template
Adminhtml : Magento\Backend\Block\Template

I hope this helps you. For any doubts regarding this topic, please write your doubts in the comments section.

Mahesh Makwana

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    TO TOP