【问题标题】:Create a new Block in Magento在 Magento 中创建一个新块
【发布时间】:2011-05-21 16:04:46
【问题描述】:

我昨天问了这个问题Static block on home page in Magento,它回答了我关于将 cms/block 连接到现有块(在该示例中为内容)的问题。

但现在我想知道如何创建自己的块。

我的 .phtml 模板中有这个:

<?php echo $this->getChildHtml('home_flash') ?>

这在我的 cms.xml 文件中

<reference name="home_flash">
  <block type="cms/block" name="home-page-flash" before="content">
    <action method="setBlockId"><block_id>home-page-flash</block_id></action>
  </block>
</reference>

但这不起作用。

我还尝试在 page.xml 文件中创建自己的块类型(通过复制面包屑声明):

<block type="page/html_home_block" name="home_block" as="home_block" template="page/template/home_block.phtml"/>

该文件存在但未呈现。

但是当我像这样引用块时:

<block type="page/html_breadcrumbs" name="home_block" as="home_block" template="page/template/home_block.phtml"/>

它呈现了我的主块模板,但原始 cms/块没有附加到它。

希望所有不同的案例都能显示正在发生的事情并突出我的知识差距足以让别人回答,我是否必须在某处“注册”我的新“home_block”类型?

【问题讨论】:

  • 不是 100% 清楚您要完成的工作,这使得理解问题变得困难。你能解释一下你想要达到的最终结果是什么,以及更具体的事情吗? (即“我的 .phtml 模板”:哪个 phtml 模板?)
  • @Alan Storm,感谢您的评论,我知道这个问题很长,我试图在最后用一行问题来总结! @clockworkgeek 回答了我的问题,结果我错过了关于 Magento 的 MVC 位的要点!

标签: php xml layout magento block


【解决方案1】:

您可以使用许多不同的块,而无需创建自己的块。在这种情况下,我认为core/text_list 是合适的,因为它不需要模板,并且可以根据需要在其中包含任意数量的子块。

<?xml version="1.0"?>
<layout version="0.1.0"><!-- All layout files start with this -->
    <cms_index_index><!-- Index directive is the same as "home" page -->
        <reference name="root"><!-- For more blocks that can be referenced see "default" directive -->
            <block type="core/text_list" name="home_flash">
                <block type="cms/block" name="home-page-flash">
                    <action method="setBlockId"><block_id>home-page-flash</block_id></action>
                </block>
            </block>
        </reference>
    </cms_index_index>

    <!-- More directives might go here -->

</layout>

其他值得了解的有用块类型是core/textcore/template,它们分别对应于Mage_Core_Block_TextMage_Core_Block_Template。他们最常被使用。
您自制的 page/html_home_block 块类型没有任何名称匹配的 PHP 类,如果您真正创建自己的块,您将无法使用 page 前缀,因为 Magento 已经这样做了。

要创建块,您只需要在布局文件中添加&lt;block&gt; 标签。
要创建块类型,您需要编写一个 PHP 类,给它一个命名空间并将其声明为模块的一部分。
添加到现有块是您使用&lt;reference&gt; 标记的时间。

Magento Knowledge Base 有很多好文章,包括Theming & Design 上的一些文章。

【讨论】:

  • 感谢您提供完整而完整的答案,我一直在努力在知识库上找到既不是超级简单也不是让我头疼的文档。我现在将研究现有的块,甚至可能会绕过 MVC 位的另一侧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-22
  • 2011-06-02
  • 2016-03-21
  • 2015-06-03
  • 1970-01-01
相关资源
最近更新 更多