Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading Magento child html outside of Magento

I am loading Magento blocks outside of Magento for certain parts of my site. I can do this successfully with something similar the following.

require_once $docRoot.'/app/Mage.php';
umask(0);
Mage::app('default');
...

$layout = Mage::getSingleton('core/layout');
$block = $layout->createBlock('Mage_Page_Block_Html_Header');
$block->setTemplate('page/html/header.phtml');
echo $block->renderView();

The problem is that if the block I am rending has child blocks(html) they are not included in the output. In the example above the file header.phtml contains the following call for child html that is missing from the output.

...
<?php echo $this->getChildHtml('topLinks') ?>
...
like image 467
Christian Avatar asked Jan 02 '11 07:01

Christian


2 Answers

A layout object is a collection of block objects. The blocks are organized in parent/child tree form.

Your layout has a single block. You have not added any child blocks to it. Therefore, when your block's template tries to render a child with getChildHtml, it can't find one, and no additional output is produced.

Additionally, the topLinks block, by default, doesn't render anything. It needs to have links added to it. This is typically done through other layout.xml files.

Finally, it's probably better to kick off rendering with a call to

echo $block_header->toHtml();

Below is an example of how you can nest blocks correctly, as well as call their action methods, such that you'll be able to render your blocks outside of the normal dispatching procedure. It's different from yours in that we create a new link block, add a link to it, and add it to your top level block.

require_once 'app/Mage.php';
umask(0);
Mage::app('default');

$layout         = Mage::getSingleton('core/layout');

$block_header   = $layout->createBlock('page/html_header')->setTemplate('page/html/header.phtml');

// <block type="" name="top.links" as="topLinks"/>
$block_links    = $layout->createBlock('page/template_links','top.links')->setTemplate('page/template/links.phtml');
$block_header->setChild('topLinks',$block_links);

//<reference name="top.links">
//  <action method="addLink" translate="label title" module="customer"><label>My Account</label><url helper="customer/getAccountUrl"/><title>My Account</title><prepare/><urlParams/><position>10</position></action>
//</reference>
$block_links->addLink('My Account','foo/baz/bar/','My Account','','',10);

echo $block_header->toHtml();
like image 72
Alan Storm Avatar answered Nov 16 '22 18:11

Alan Storm


The link below provides a somewhat similar approach like the one Alan mentioned although this involves adding other blocks which may contain JS files and CSS. You might wanna try checking it out too:

How to add Magento blocks, CSS and Javascript to an external site

like image 2
Richard Feraro Avatar answered Nov 16 '22 17:11

Richard Feraro