Recursivity in smarty
| From: | Christopher Rousseau | Date: | Thu, 10 Apr 2003 08:23:58 +0000 |
| Subject: | Recursivity in smarty | ||
| Groups: | php.smarty.general | ||
| Request: | Send a blank email to php-smarty-general+get-9207@lists.php.net to get a copy of this message | ||
Hello,
I was encounter a small limite using smarty : recursivity
I have this type of class :
Class X {
getChildren() {
// Some code to create a list of children
return $arrayOfChildren ; // Array of Object
instanciate from class X (again, and again, and again,
)
}
}
I was using it for the creation of infinitly recursive menu.
But I was not able to write my recurive menu using Smarty. Its why I
have create this small plugin :
------------------------------------------------------------------------
---
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* Author : Christopher Rousseau <christopher.rousseau@wanadoo.fr>
* Type: function
* Name: recursive
* Purpose: execute another smarty template inside a template smarty
* Parameters:
* template: template name
* [param] : all else parameter will be assigned to
* the new smarty instance
* -------------------------------------------------------------
*/
function smarty_function_recursive($params, &$smarty)
{
if
(!array_key_exists('template',$params)||$params['template']==Null) {
$smarty->trigger_error("assign: missing 'template' parameter");
return;
}
$recursiveSmarty = new Smarty();
$recursiveSmarty->template_dir = $smarty->template_dir;
$recursiveSmarty->compile_dir = $smarty->compile_dir;
foreach($params as $key => $value) { // we assign all
else parameter to the new Smarty
if ($key!='template')
$recursiveSmarty->assign($key, $value);
}
return $recursiveSmarty->fetch("$params[template]");
}
?>
This plugin instanciate a new Smarty with the same configuration.
Im currently use it like that :
I assign my root menu in $list variable, $list is an array of object X
Root.tpl :
------------------------------------------------------------------------
---
<ul>
{foreach from=$list item=menu}
{recursive template='recursive.tpl' menu=$menu}
{/foreach}
</ul>
------------------------------------------------------------------------
---
recursive.tpl :
<li>
{$menu->getField('name')}
<ul>
{foreach from=$menu ->getChildren() item=children}
{recursive template='recursive.tpl' menu=$children}
{/foreach}
</ul>
</li>
------------------------------------------------------------------------
---
I think I have forget some configuration to pass thru the recursive
Smarty (like cache configuration). But those parameter was anough for me
(I cache the root template).
Hop it can be usefull for some of you,
Bye.
Christopher Rousseau