Functions and recursion in Smarty Templates

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}
<ul>
{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}
{/if}
</li>
{/foreach}
</ul>
{/function}
 
{* Call the function with the root  *}
{call render_menu items=$menu}