问题
I asked this question yesterday Static block on home page in Magento, which answered my question about hooking a cms/block to an existing block (content, in that example).
But now I would like to know how to create my own block.
I have this in my .phtml template:
<?php echo $this->getChildHtml('home_flash') ?>
And this in my cms.xml file
<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>
But this is not working.
I have also tried to create my own block type, (by copying the breadcrumbs declaration) in the page.xml file:
<block type="page/html_home_block" name="home_block" as="home_block" template="page/template/home_block.phtml"/>
That file exists but isn't being rendered.
However when I reference the block like this:
<block type="page/html_breadcrumbs" name="home_block" as="home_block" template="page/template/home_block.phtml"/>
It renders my home block template, but the original cms/block is not attached to it.
Hope all the different cases show what is happening and highlight the gap in my knowledge well enough for someone to answer, do I have to "register" my new "home_block" type somewhere?
回答1:
There are many different blocks available that you can use without creating your own. In this case I think core/text_list
would be suitable because it doesn't require a template and can have as many child blocks within it as you need.
<?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>
Other useful block types worth knowing are core/text
and core/template
which correspond to Mage_Core_Block_Text
and Mage_Core_Block_Template
respectively. They get used the most.
Your home made block type of page/html_home_block
didn't have any PHP class with a matching name, and if you were genuinely creating your own you wouldn't be able to use the page
prefix since Magento already does.
To create a block you only need a <block>
tag in the layout file.
To create a block type you need to write a PHP class, give it a namespace and declare it as part of a module.
To add to an existing block is the time when you use a <reference>
tag.
There are many fine articles at Magento Knowledge Base including some on Theming & Design.
来源:https://stackoverflow.com/questions/4378329/create-a-new-block-in-magento