Magento 2 – How to Call Helper Method in .phtml File

helpermagento2phtml

Trying to develop something in magento 2. But, I didn't find how to call a Helper method in template(.phtml) file.

I want a replacement of below code:

$this->helper('modulename/helpername')->methodname();

If anyone knows please help me.

Best Answer

You should not use helper calls directly in the template.
Have your helper instance provided as a dependency to the block that renders the template and create a method in your block that calls the helper and call that method in the template.

Have your block defined like this

protected $helperData;
public function __construct(
     ....
    \{Vendor}\{Module}\Helper\Data $helperData,
    ....
) {
    ....
    $this->helperData = $helperData;
    ....
}

public function doSomething()
{
    return $this->helperData->doSomething();
}

Then you can call in your template $block->doSomething()

Related Topic