Functions and recursion in Smarty Templates

October 10, 2012 · Posted in Development 

The code below defines a recursively callable function in the Smarty template itself and calling it. For example, it renders hierarchical menu when the level of the tree is not known and can be deep.


{* Define the function *}
{function name=render_menu level=0}
{foreach $items as $item}
<li><a href="{$item->url}">{$item->title}</a>
{if count($item->submenus) > 0}
{call name=render_menu items=$item->submenus level=$level+1}
{* Call the function with the root  *}
{call render_menu items=$menu}