Recursive Nav Examples

Statamic's nav tag is capable of some pretty rad stuff, but recursion can be a little bit hard on the old brain (on the old brain).

Let’s say we have the following pages:

Pages hierarchy example

Maybe you would like to render a footer hierarchy, with top level pages as <h3>’s, direct sub-items as <li> items, while ignoring anything deeper than level 2 in the nav structure:

Footer nav example

We can do this by performing a depth check to decide how to render the current item based on it’s depth in the nav structure:

<div class="flex">
    {{ nav }}
        {{ if depth == 1 }}
            <div class="mx-10">
                <h3 class="mb-2">{{ title }}</h3>
                {{ if children }}
                    <ul>{{ *recursive children* }}</ul>
                {{ /if }}
            </div>
        {{ elseif depth == 2 }}
            <li class="my-1">
                <a href="{{ url }}">{{ title }}</a>
            </li>
        {{ /if }}
    {{ /nav }}
</div>

Or maybe you would like to render a sidebar style nav as a <ul>, while applying a different css class based on the page’s depth in the nav structure:

Sidebar nav example

Here we dynamically insert a CSS class based on the current item’s depth in the nav structure:

---
nav_classes:
  1: 'font-gray-900 font-bold'
  2: 'text-gray-800 ml-3'
  3: 'text-gray-500 ml-6 text-sm'
---

<ul class="leading-loose">
    {{ nav }}
        <li>
            <span class="{{ view:nav_classes[depth] }}">
                {{ title }}
            </span>
            {{ if children }}
                <ul class="{{ depth == 1 ?= 'mb-4' }}">
                    {{ *recursive children* }}
                </ul>
            {{ /if }}
        </li>
    {{ /nav }}
</div>
Betterify this page on Github!