Question

In Magento 1 I can Inject a template through coding like below.

$layout = Mage::getSingleton('core/layout');
$block = $layout->createBlock('module/module_block_identifier');
$block->setTemplate('module/test.phtml');

In Magento 2, how can I inject a template like above?

Was it helpful?

Solution

You can using:

$block = $this->getLayout()->createBlock(
            'Magento\Backend\Block\Template'
        )->setTemplate('module/test.phtml');

Class \Magento\Framework\View\Result\Layout as Mage::getSingleton('core/layout')

OTHER TIPS

If you are inside a block class you can simply use:

$layout = $this->getLayout(); 
....

If you are in a controller you need to inject in the constructor an instace of \Magento\Framework\View\LayoutFactory and use that:

protected $layoutFactory;
public function __construct(
    ...
    \Magento\Framework\View\LayoutFactory $layoutFactory,
    ....
) {
    ...
    $this->layoutFactory = $layoutFactory;
    ...
}

And later you can use this:

$layout = $this->layoutFactory->create(); 
$block = $layout->createBlock(....)
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top