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:
1. Call directly helper class
$helper = $this->helper([Vendor]\[Module]\Helper\Data); $values = $helper->HelperMethod();
2. Using block class
<?php namespace [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(); } }
If you want to call block in template file like display.phtml, write $block->yourMethod(); 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.
Feel free to share the post with fellow developers via social media.
Thanks.