0

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

<?php print $this->getLayout()
                 ->createBlock("catalog/product_view")
                 ->setTemplate("catalog/product/view/addto.phtml")
                 ->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

0
1

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

$layout->createBlock(ClassName)->setTemplate('template_file')->toHtml();

In the template, you can use

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

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