How To Create A Block From Controller Magento 2 : Here we will learn how to create block from controller or call a phtml file from controller.
1 => check the below code
/**
* @var Magento\Framework\View\Result\PageFactory
*/
protected $_resultPageFactory;
/**
* @param Context $context
* @param PageFactory $resultPageFactory
*/
public function __construct(
Context $context,
PageFactory $resultPageFactory
) {
$this->_resultPageFactory = $resultPageFactory;
parent::__construct($context);
}
public function execute()
{
$resultPage = $this->_resultPageFactory->create();
$resultPage->getConfig()->getTitle()->prepend(__(' heading '));
$block = $resultPage->getLayout()
->createBlock('Companyname\Module\Block\blockname')
->setTemplate('Companyname_Module::test.phtml')
->toHtml();
$this->getResponse()->setBody($block);
}
}
Please be ensure that your block file and phtml file is also created earlier.
Hope so it will help you.
1 comments