In magento 1 I could create a block/ attach a phtml to it and then call it as follows ;

<?php print $this->getLayout()
                 ->toHtml(); ?>

is it possible in magento 2 to create a block and then attach a phtml file without using a layout.xml.

the reason for asking is that i dont want to attach the layout to a specific page/default but wish to call it in whatever location I want


1 Answer 1


Yes sure you can do that with \Magento\Framework\View\LayoutInterface $layout,


In the template, you can use

echo $block->getLayout()->createBlock(ClassName)->setTemplate('template_file')->toHtml();
  • if i call this within my phtml page, where would the $layout variable come from?
    – theSeeker
    Nov 30, 2018 at 15:19
  • You can using $block->getLayout().
    – HoangHieu
    Nov 30, 2018 at 15:53

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