4

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?

2

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')

9

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(....)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.