使用之前/之后放置块的Magento XML几乎不起作用

mik*_*rce 41 xml magento

我是一个前端Magento开发者,已经构建了我自己的一些主题,我想更好地理解Magento的XML块定位...

我通常使用一个local.xml文件来操作一切,我可以按如下方式定义一个块:

<cms_index_index>
   <reference name="root">
      <block type="core/template" name="example_block" as="exampleBlock" template="page/html/example-block.phtml"/>
   </reference>
</cms_index_index>
Run Code Online (Sandbox Code Playgroud)

这将在主页(cms_index_index)上创建一个块,并且由于块创建了一个级别root,我通常会通过添加以下内容来调用块:

<?php echo $this->getChildHtml('exampleBlock') ?>
Run Code Online (Sandbox Code Playgroud)

......到1column.phtml(或2columns-left/ right.phtml,3columns.phtml等等).可以通过替换cms_index_index适当的页面标记将块放置在任何页面上.

我在整个核心XML文件和教程中看到如下内容:

<reference name="root">
   <block type="core/template" name="example_block" before="content" template="page/html/example-block.phtml"/>
</reference>
Run Code Online (Sandbox Code Playgroud)

content是一个块,它是magento的一般页面结构的一部分,从我的理解,before="content"应该把它放在你期望的地方,而不需要使用getChildHtml('exampleBlock'),到目前为止那么好...但是,之前/之后似乎几乎没有工作我,我经常发现自己使用getChildHtml方法作为备份,这并不总是理想的,并且意味着编辑更多.phtml文件而不是必要的.

我试过了:

<reference name="root">
   <block type="core/template" name="example_block" before="content" template="page/html/example-block.phtml"/>
</reference>
Run Code Online (Sandbox Code Playgroud)

什么都没出现......

<reference name="root">
   <block type="core/template" name="example_block" after="header" template="page/html/example-block.phtml"/>
</reference>
Run Code Online (Sandbox Code Playgroud)

仍然没有....我也知道在它的父块之前使用before="-"after="-"放置一些东西.我偶尔会有一些运气,但一般只会感到困惑和沮丧.

我已经搜索了"magento xml之前/之后不工作"的地方,并开始怀疑它是否只是我发生这种情况......任何人都可以解释我什么时候可以使用之前/之后定位块?上面的例子有什么问题?

我在magento 1.7.0.2(发布时最新的)

这样做的主要动机是减少我需要编辑的核心.phtml文件的数量,只是为了添加一个getChildHtml(),所以如果有另一种(XML)方式来解决这个问题,我有兴趣知道......

Ala*_*orm 86

beforeafter属性只有在两种情况之一的工作:

  1. 插入core/text_list块时
  2. 模板块调用时getChildHtml没有任何参数

当你说

<reference name="root">
   <block type="core/template" name="example_block" before="content" template="page/html/example-block.phtml"/>
</reference>
Run Code Online (Sandbox Code Playgroud)

你在告诉Magento

嘿Magento,把example_block内部root挡住了.

当您在父项中放置许多不同的块时,这些块具有隐式顺序.对于模板块,此顺序无关紧要,因为这些块是显式呈现的.

<?php echo $this->getChildHtml('example_block') ?>
Run Code Online (Sandbox Code Playgroud)

但是,有两种情况下订单很重要.首先,如果你打电话

<?php echo $this->getChildHtml() ?>
Run Code Online (Sandbox Code Playgroud)

从模板中,Magento将按顺序渲染所有子块.

其次,有一种称为"文本列表"(core/text_list/ Mage_Core_Block_Text_List)的特殊类型的块.这些块再次按顺序自动渲染所有子节点.该content块就是一个例子

<block type="core/text_list" name="content"/>
Run Code Online (Sandbox Code Playgroud)

这就是为什么你可以插入块content并自动渲染的原因.

因此,在上面的示例中,您将块插入root块中.该root块是一个模板块,其phtml模板使用getChildHtml带有显式参数的调用.因此,这些beforeafter属性并没有做到你(以及许多其他人,包括我)希望他们做的事情.

  • 谢谢你让它变得更好,更清楚,我现在明白了:) (4认同)