4

I am trying to generate a nested menu of all the pages in the site tree.

The docs show two levels - I won't know how many levels there are.

Currently I know there is at least four levels deep at one point so I have this:

<ul>
<% loop $Menu(1) %>
    <li>
        <a href="$Link" title="Go to the $Title page" class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>">
            $MenuTitle
        </a>

        <% if $Children %>
        <ul>
        <% loop $Children %>
            <li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>">
                <a href="$Link">$MenuTitle</a>

                <% if $Children %>
                <ul>
                <% loop $Children %>
                    <li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>">
                        <a href="$Link">$MenuTitle</a>

                        <% if $Children %>
                        <ul>
                        <% loop $Children %>
                            <li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>">
                                <a href="$Link">$MenuTitle</a>
                            </li>
                        <% end_loop %>
                        </ul>
                        <% end_if %>

                    </li>
                <% end_loop %>
                </ul>
                <% end_if %>

            </li>
        <% end_loop %>
        </ul>
        <% end_if %>

    </li>
<% end_loop %>
</ul>

It works but is unreliable (if an editor adds another level). It is pretty janky. Is there a recursive option?

3dgoo
  • 15,716
  • 6
  • 46
  • 58
polycode
  • 135
  • 7

1 Answers1

3

We can create a recursive menu item template to create a menu that goes as deep as the site tree.

First we create a MenuItem.ss template file in our theme's Includes directory. In this template we display the menu item link and check if there are any children pages. We loop through any children pages and include the MenuItem.ss template for each:

Includes/MenuItem.ss

<li class="$LinkingMode">
    <a href="$Link" aria-label="Go to the $Title.XML page">$MenuTitle</a>

    <% if $Children %>
    <ul>
        <% loop $Children %>
        <% include Includes/MenuItem %>
        <% end_loop %>
    </ul>
    <% end_if %>
</li>

Our main menu code in our template then becomes the following:

<nav class="main-menu">
    <ul>
        <% loop $Menu(1) %>
        <% include Includes/MenuItem %>
        <% end_loop %>
    </ul>
</nav>
3dgoo
  • 15,716
  • 6
  • 46
  • 58