Search code examples
magentomagento-layout-xml

Adding template block to another block dynamically for a module


I'm trying to add a template block to my footer block in the product view (only), the product detail page. I've tried the following in the catalog.xml layout file, but with no luck:

<catalog_product_view translate="label">
  ...
  <reference name="footer">
      <block type="core/template" name="uniqueName" template="catalog/product/mytemplate.phtml" />
  </reference>
</catalog_product_view>

and

<catalog_product_view translate="label">
  ...
  <reference name="footer">
      <block type="core/template" name="uniqueName">
          <action method="setTemplate"><template>catalog/product/mytemplate.phtml</template></action>
      </block>
  </reference>
</catalog_product_view>

I was able to put the template block into the content block using the latter method the same way, <reference name="content">, so I don't understand why this isn't working. It seems like I'm not referencing the footer properly.. I see in the page.xml file the footer being created added as <block type="page/html_footer" name="footer" as="footer" template="page/html/footer.phtml">. Can somebody help me figure this out? Much appreciated!


Solution

  • In page.xml, take a look at the layout update xml fragment that instantiates the content block object

    <block type="core/text_list" name="content" as="content" translate="label">
    

    The content block is core/text_list block. The core/text_list blocks automatically render their child blocks (i.e. they're a contain block for a list of text blocks). The core/text_list alias resolves to Mage_Core_Block_Text_List, take a look at this classes rendering method to see why appending things to your content block works.

    Now, take a look at the layout update XML fragment that instantiates the footer block.

    <block type="page/html_footer" name="footer" as="footer" template="page/html/footer.phtml">
    

    The foot block is not a text list block. It's a page/html_footer block, which is a template block. You can determine this by looking at the class that the page/html_footer block inherits from

    class Mage_Page_Block_Html_Footer extends Mage_Core_Block_Template
    

    Template blocks do not automatically render all their child blocks. Instead, inside the block's template, you must explicitly render a child with a call to

    echo $this->getChildHtml('block_name'); 
    

    So when you say

    <reference name="footer">
         <block type="core/template" name="uniqueName" template="catalog/product/mytemplate.phtml" />
    </reference>
    

    you're telling Magento to insert a block named uniqueName as a child block of the footer block. However, in order to render the block, the footer's template must call

    $this->getChildHtml('uniqueName')