سؤال

Is there a simple way as in magento1 :

 $crumbs = Mage::app()->getLayout->getBlock('breadcrumbs');
هل كانت مفيدة؟

المحلول


OUTDATED: ANSWER REFERS TO MAGENTO 2 ALPHA


I wish it was that easy.
It depends on where you want to instantiate it from.
If you want to create an instance from inside an other block do it like this:

$this->getLayout()->createBlock('Full\Block\Class\Name\Here');

From inside a controller do this:

 $this->_view->getLayout()->createBlock('Full\Block\Class\Name\Here');

From inside a model:

 $this->_blockFactory->createBlock('Full\Block\Class\Name\Here');

but here there is a catch.
you have to create a protected member on the model called _blockFactory and inject an instance of \Magento\Framework\View\Element\BlockFactory in the constructor and assign it to that member var.

Something like this:

protected $_blockFactory;
public function __construct(
   ...,
   \Magento\Framework\View\Element\BlockFactory $blockFactory,
   ....
){
    ....
    $this->_blockFactory = $blockFactory;
    ....
}

For instantiating a block from inside a helper it works the same as for model

نصائح أخرى

To instantiate a block you have to use \Magento\Framework\View\LayoutInterface class and its createBlock() method.

With an helper class you could do it with this code:

namespace Vendor\Module\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{

    /**
     * Layout
     *
     * @var \Magento\Framework\View\LayoutInterface
     */
     protected $_layout;


    /**
     *
     */
     public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\View\LayoutInterface $layout
     ) {
         $this->_layout = $layout;
         parent::__construct($context);
     }


    /**
     * Create new block
     */
     public function getBlock() {

        $block = $this->_layout
            ->createBlock('Magento\Framework\View\Element\Template')
            ->setTemplate('Vendor_Module::helper/block.phtml');

        return $block;

     }

}

Then call $helper->getBlock() from where you need.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى magento.stackexchange
scroll top