How to Call Helper Function in phtml in Magento 2
Helper classes offer functionalities for many features in Magento 2 stores. With Magento 2, the Helper can be called in controllers, models, views and other helpers.
The below code can be used when you want to have helper’s data in .phtml file in Magento 2.
Making changes in the default Magento 2 files is not advisable and that’s when the Magento 2 Helper class comes in picture to override the core files.
The programmatic method to call helper function in phtml in Magento 2 as given below can be helpful to implement custom functionalities and enhance the store features!
Method to Call Helper Function in phtml in Magento 2:
- Call directly helper class
12$helper = $this->helper([Vendor]\[Module]\Helper\Data);$values = $helper->HelperMethod(); - Using block class
123456789101112131415161718192021222324<?phpnamespace [Vendoe]\[Module]\Block;class BlockName extends \Magento\Framework\View\Element\Template{protected $helper;public function __construct(....[Vendor]\[Module]\Helper\Data $helperData,....) {....$this->helper = $helperData;....}public function yourMethod(){return $this->helper->methodName();}}Here, BlockName class is block that renders the template display.phtml file.
That’s it.
You may also refer the programmatic method to call CMS static block in pHTML file in Magento 2.
Any doubts? Mention them in the Comments section below. I’d be happy to help.
Feel free to share the post with fellow developers via social media.
Thanks.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How To Enable GZIP Compression for Magento
How to Configure Magento Cron Job
Next