4

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');
minlare
  • 2,454
  • 25
  • 46

2 Answers2

3

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?

Chris Anderson
  • 231
  • 1
  • 10
1

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.

Sintu Roy
  • 155
  • 9