2

I want to create a block dynamically but not render it within the layout hierarchy (I am going to save the output).

Is there any reason to use Layout::createBlock() in this case or can I instantiate it directly with a factory? Or even inject the block itself as shared instance into the class where I'm using it?

I would prefer to avoiding the unnecessary dependency to the layout and the additional abstraction but I am not sure what might break if the block is not associated to the layout.

2

if you don't do it via Layout::createBlock some of the methods you might call from that block will throw exceptions or return an empty string.
Here are some examples (all of them from \Magento\Framework\View\Element\AbstractBlock):

  • getChildNames
  • setChild
  • addChild
  • unsetChild
  • unsetChildren
  • getChildBlock
  • getChildHtml
  • getChildChildHtml
  • getBlockHtml
  • insert
  • append
  • getGroupChildNames

I would advice to use the createBlock if you want to be politically correct, but if you don't need any of the methods above I see no harm in using the block as a shared instance.

  • I found out that the block still has access to the layout because it is passed on construction via context object, but after checking "addChild" and related methods, I understand that they throw exceptions because $this->_nameInLayout is empty. Thanks for the hint! – Fabian Schmengler Sep 22 '16 at 8:47
1

Layout::createBlock() is useful if the block is a CMS block or page that has {{...}} content such as widgets or variables. If you don't go through the layout, you won't get these elements.

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.