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.

 

[codesyntax lang=”php”]

{* 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}

[/codesyntax]

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>