在Magento 2中如何从布局中检索容器?

时间:2016-06-24 12:00:23

标签: magento2 magento-layout-xml

如何以编程方式从布局中检索容器?

我希望能够做到以下几点......

<picture>
   <source media="(min-width: 980px)" srcset="@(Configuration.URLs.MediaPath + ad.ImagePath)" />
   <img class="post__featured-image" data-lazy="@(Configuration.URLs.MediaPath + ad.SmallImagePath)" />
</picture>

2 个答案:

答案 0 :(得分:1)

核心调试很少,我发现有一种方法 使用name作为参数返回任何容器,块或UIcomponent html。

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

*用您的块,容器或UI组件名称替换top-right-wrapper。

答案 1 :(得分:1)

所以我将成为那个家伙,请尽最大努力不要直接使用对象管理器。 To use or not to use the ObjectManager directly?

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

以上两种方法都可以,但是不建议使用$ this。 Magento 2 Templates: Use $block or $this?