In Magento 2 how can I retrieve a container from layout?

3.2k views Asked by At

How can I retrieve a container from the layout programmatically?

I would like to be able to do something like the following...

$container = $layout->getContainer('name');
$container->setAttribute('htmlClass', 'class');
2

There are 2 answers

0
Sintu Roy On

With little debugging in core I have found that there is a method which returns any container,block or UIcomponent html using name as parameter.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$layoutObj = $objectManager->get('Magento\Framework\View\Layout');
$html = $layoutObj->renderNonCachedElement('top-right-wrapper');
echo $html;

* Replace top-right-wrapper with your block,container or UIcomponent name.

0
Chris Anderson On

So I'll be that guy, try your best not to use the object manager directly. To use or not to use the ObjectManager directly?

<?= $block->getLayout()->renderNonCachedElement('top-right-wrapper'); ?>
-or-
<?= $this->getLayout()->renderNonCachedElement('top-right-wrapper'); ?>

Both above will work but using $this is discouraged. Magento 2 Templates: Use $block or $this?