"Saruman believes it is only great power that can hold evil in check, but that is not what I have found. I found it is the small everyday deeds of ordinary folk that keep the darkness at bay. Small acts of kindness and love." --Gandalf

How to call any block in any phtml template in Magento 2

Thursday, May 6th, 2021

In Magento 2, it's possible to call any block into any phtml with two lines of code. Ideally, dependency injection should be used but I'll demonstrate both methods. I will use FirstModule and SecondModule to distinguish between the two modules.

The correct way

In the Block construct for your FirstModule phtml:

namespace Vendor\FirstModule\Block;

class Custom extends Template

private $custom;

public function __construct(
 \Vendor\SecondModule\Block\Custom $custom
) {
 $this->custom = $custom;

public function getCustomMethod()
 // This references the "SecondModule" Custom class
 $custom = $this->custom;
 // Returns the getCustomMethod() from the "SecondModule"
 return $custom->getCustomMethod();

In the FirstModule phtml where the SecondModule "getCustomMethod" output will be displayed:

<?= $block->getCustomMethod(); ?>

The not-as-correct way that also works (no injection)

In the FirstModule phtml where the custom SecondModule output will be displayed:

 $customBlock = $block->getLayout()->createBlock('Vendor\SecondModule\Block\Custom');
 echo $customBlock->getCustomMethod();

Views: 334