Page 1 of 1

Recursive Menu

Posted: Wed Dec 17, 2008 5:01 pm
by duclet
After some tinkering this morning, I have figured out how to display the menu using recursion. It requires some extra code of course but compared to all the {repeat} stuff in the normal menu, this to me looks better on the eye and easier to understand.

First up, the code for the menu template:

Code: Select all

<ul>
{foreach from=$nodelist item=node name=recursive_menu}
    {* The first time around, we should display everything, all the other time
       we should ignore the first element since we should have already displayed
       it.
    *}
    {if !isset($tmp_starting_recursion) || !$smarty.foreach.recursive_menu.first}
        <li>
            {cms_selflink page=$node->alias}
            {if $node->haschildren}
                {* Let future calls know that the recursion has begun so that it
                   would skip displaying the first item.
                *}
                {assign var=tmp_starting_recursion value=true}

                {* This will display all menu items that is the children of the
                   current alias including that alias (that is why we need to skip
                   displaying it with the first if statement). Try to keep everything
                   the same here except the templat name which should be the same
                   name of the template you are currently editing.
                *}
                {menu start_page=$node->alias number_of_levels=2 template='Recursive'}
            {/if}
        </li>
    {/if}
{/foreach}
</ul>
Next up, we need to call this in the page or template with the following:

Code: Select all

{* Reset the temp variable so we can call this recursive menu more than once. No need
   for this if we are only calling the menu once.
*}
{assign var=tmp_starting_recursion value=false}

{* Call the menu with only the first level as the menu will take care of all the
   lower elements.
*}
{menu template='Recursive' num_of_levels=1}
I believe the comments should be able to explain it all. However, if you have any questions, feel free to ask.

Re: Recursive Menu

Posted: Sat Dec 27, 2008 9:36 pm
by duclet
I have made an update to this that makes this even easier. Take a look at the updated code:

Code: Select all

<ul>
{foreach from=$nodelist item=node}
    <li>
        {cms_selflink page=$node->alias}
        {if $node->haschildren}
            {menu start_element=$node->hierarchy|cat:'.1' number_of_levels=1 show_root_siblings=1 template='Recursive'}
        {/if}
    </li>
{/foreach}
</ul>
Now we do not need the variable tmp_starting_recursion anymore. Just make sure when you are calling the menu, it is still the same as it was before.