6

请遵循以下代码,该代码取自我的 Magento Commerce 主题:

从 layout/page.xml 中提取

<block type="page/html_header" name="header" as="header">
    <block type="page/template_links" name="top.links" as="topLinks"/>
    <block type="page/switch" name="store_language" as="store_language" template="page/switch/languages.phtml"/>
    <block type="page/switch" name="store_switcher" as="store_switcher" template="page/switch/stores.phtml"/>
    <block type="directory/currency" name="store_currency_selector" as="store_currency_selector" template="directory/currency_top.phtml"/>
    <block type="core/text_list" name="top.menu" as="topMenu" translate="label">
        <label>Navigation Bar</label>
        <block type="page/template_links" name="top.links.mobile" as="topLinksMobile"/>
        <block type="checkout/cart_sidebar" name="cart_sidebar_mobile" as="cartSidebarMobile" template="checkout/cart/topbar.phtml"/>
    </block>
    <block type="page/html_wrapper" name="top.container" as="topContainer" translate="label">
        <label>Page Header</label>
        <action method="setElementClass"><value>top-container</value></action>
    </block>
    <block type="checkout/cart_sidebar" name="cart_sidebar" as="topcart" template="checkout/cart/topbar.phtml"/>
</block>

从模板/目录/导航/top.phtml中提取

<li class="level0 nav-2 active level-top first parent">
    <a href="javascript:;">ACCOUNT</a>
    <?php echo $this->getParentBlock()->getChildHtml('topLinksMobile'); ?>
</li>
<li class="level0 nav-3 active level-top first parent">
    <a href="javascript:;">CART</a>
    <?php echo $this->getChildHtml('cartSidebarMobile'); ?>
</li>

基本上,我想要做的是在“topMenu”块内创建两个子块,然后使用“getChildHtml”函数将它们打印到模板中。

不幸的是,我的函数调用失败了,而这两个块是在我的 top.phtml 生成内容之前加载的。

请给我一些关于我做错了什么的建议。

提前谢谢了。

4

3 回答 3

0

在以下文件中尝试调用函数 template/page/html/topmenu.phtml

于 2013-05-17T07:47:51.227 回答
0

我进步了一点。

通过阅读:Magento - 显示块,但仅在我使用 getChildHtml 调用它时显示

和:了解 Magento 块和块类型

我知道core/text_list 会自动打印内容,所以我将类型更改为“page/html_wrapper”。

问题是现在这两个元素的内容是重复的。一次在 top.phtml 的内容之前,第二次在调用 getChildHtml 时。

任何想法将不胜感激。

于 2013-05-17T09:30:55.590 回答
0

getChildHtml 方法是块/模板的真正力量。它允许您渲染辅助块(“子块”)内的所有块。在主块(“父”)内。块调用块调用块是为您的页面创建整个 HTML 布局的方式。

格式:

getChildHtml('block_name'); ?>

注意:在 PHTML 模板文件中使用 $block 而不是 $this,因为根据 Magento 2 编码标准,不鼓励使用 $this

如果该命令可以在任何地方的模板文件中找到 block_name,它将为您获取 block_name 的 HTML,只有当 block_name 是当前块的子级时。

例如,让我们看一下 module-wishlist 的模板文件 (view.phtml) 的摘录:

helper(\Magento\Wishlist\Helper\Data::class)->isAllow()) : ?>
<div class="toolbar wishlist-toolbar"><?= $block->getChildHtml('wishlist_item_pager'); ?></div>
<?= ($block->getChildHtml('wishlist.rss.link')) ?>

在这里,我们可以看到愿望清单工具栏类的内容由块呈现:wishlist_item_pager 和wishlist.rss.link。这些块是子块,在 wishlist_index_index.xml 中定义(位于 vendor\magento\module-wishlist\view\frontend\layout):

注意:getChildHtml 方法只能包含布局中指定为子块(子块)的块。这允许 Magento 仅实例化它需要的块,还允许您根据上下文为块设置不同的模板。
于 2022-01-31T07:03:22.397 回答