Developer guide     >     Developing Templates     >     Examples

Rendering menus

Recursive rendering of $tree

This is the preferred method of outputting trees. Especially when you want to render an unlimited number of levels we recommend the recursive rendering method making use of a nested tree.
  1. {assign var="ntree" value=$tree|@nest_tree}
  2. {definefunc name="render_menu" list=$ntree}
  3.     <ul>
  4.     {foreach from=$list item=element}
  5.         {if $element.NAVIGATIONCODE == "main_menu"}
  6.         <li{if $element.SELECTED} class="selected"{/if}>
  7.             <a href="{$element.URL}">{$element.NAME}</a>
  8.             {if $element.CHILDREN}{execfunc name="render_menu" list=$element.CHILDREN}{/if}
  9.         </li>
  10.         {/if}
  11.     {/foreach}
  12.     </ul>
  13. {/definefunc}

Outputting a fixed number of levels

You don't need to use recursion in case you just want to output a fixed number of levels. In that case you just might want to use something like:
  1. <ul>
  2. {foreach from=$tree item=element}
  3.     {if ($element.NAVIGATIONCODE == "menu_main") && ($element.LEVEL == 2)}
  4.         <li><a href="{$element.URL}"{if $element.SELECTED || $element.SUBOPEN == 1} class="active"{/if}>{$element.NAME}</a>
  5.         {if $element.HASVISIBLESUBNODES == 1}
  6.             <ul>
  7.             {foreach from=$tree item=elementinner}
  8.                 {if ($elementinner.LEVEL == 3) && ($elementinner.PARENT == $element.ID)}
  9.                 <li><a href="{$elementinner.URL}"{if $elementinner.SELECTED} class="active"{/if}>{$elementinner.NAME}</a></li>
  10.                 {/if}
  11.             {/foreach}
  12.             </ul>
  13.         {/if}
  14.         </li>
  15.     {/if}
  16. {/foreach}
  17. </ul>