Magento – Add Top Links on condition basis in magento

blockslayoutmagento-1.7

I am little bit stuck with adding top links in my custom phtml. I removed the links block in my XML <remove name="top.links"/>, now after some condition become true, I want to add this block again. When I use this code for top menu it works but not for links :

$block = Mage::getSingleton('core/layout');     
echo $block->createBlock('catalog/navigation')->setTemplate('catalog/navigation/top.phtml')->toHtml();

This works and display top menu. But the below code doesn't show anything.

$block = Mage::getSingleton('core/layout');
echo $block->createBlock('page/template_links')->setTemplate('page/template/links.phtml')->toHtml();

Any help?

Best Answer

The second piece of code actually works but it does not display anything because there are no links attached to the block.
page/template/links.phtml starts with this:

<?php $_links = $this->getLinks(); ?>
<?php if(count($_links)>0): ?> 

If there are no links there is nothing to display. You need to add links to your block. Something like this:

$block = Mage::app()->getLayout()->createBlock('page/template_links');
$title = $label = Mage::helper('customer')->__('My Account');
$url = Mage::helper('customer')->getAccountUrl();
$prepareUrl = false;
$urlParams = array();
$position = 10;
$liParams=null;
$aParams=null;
$beforeText=''; 
$afterText='';
$block->addLink($label, $url, $title, $prepareUrl, $urlParams, $position, $liParams, $aParams, $beforeText, $afterText);
//add more links here
echo $block->setTemplate('page/template/links.phtml')->toHtml();

Not all parameters are mandatory for the addLink method. I just added them here so you can see all the possibilities. For more info take a look at this method: Mage_Page_Block_Template_Links::addLink().