Magento 2 – How to Call Custom phtml File in Another phtml File

blocksmagento2template

I'm trying to output custom phtml content of Lapisbard_General::customer_account.phtml in Magento_directory::currency.phtml

If I'm using below code, it works fine.

echo $this->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setTemplate("Lapisbard_General::customer_account.phtml")->toHtml();

But when I'm trying to use my custom block as below, it throws error

echo $this->getLayout()->createBlock("Lapisbard\General\Block\CustomerAccount")->setTemplate("Lapisbard_General::customer_account.phtml")->toHtml();

Fatal error: Call to a member function dispatch() on null in
/var/www/html/lapis/vendor/magento/framework/View/Element/AbstractBlock.php
on line 637

Block code:

namespace Lapisbard\General\Block;
use Magento\Customer\Model\Session;

class CustomerAccount extends \Magento\Framework\View\Element\Template {
    public function __construct(
        Session $customerSession
    )
    {
        $this->_customerSession = $customerSession;
    }
    public function isCustomerLoggedIn() {
        return $this->_customerSession->isLoggedIn();
    }
}

How can I make it work ?

Best Answer

Replace below code with your block code

namespace Lapisbard\General\Block;
use Magento\Customer\Model\Session;

class CustomerAccount extends \Magento\Framework\View\Element\Template {
    public function __construct(\Magento\Framework\View\Element\Template\Context $context,
        Session $customerSession
    )
    {
        parent::__construct($context);
        $this->_customerSession = $customerSession;
    }
    public function isCustomerLoggedIn() {
        return $this->_customerSession->isLoggedIn();
    }
}

Then you can use it

echo $this->getLayout()->createBlock("Lapisbard\General\Block\CustomerAccount")->setTemplate("Lapisbard_General::customer_account.phtml")->toHtml();
Related Topic