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

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

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


You can using:

$block = $this->getLayout()->createBlock(

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

| improve this answer | |

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(....)
| improve this answer | |

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.