Skip to content Skip to footer navigation
You are reading the docs for an old version of Statamic. Consider upgrading to Statamic 6.

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>
<div class="flex">
<s:nav>
@if ($depth == 1)
<div class="mx-10">
<h3 class="mb-2">{{ $title }}</h3>
@if (count($children) > 0)
<ul>@recursive_children</ul>
@endif
</div>
@elseif ($depth == 2)
<li class="my-1">
<a href="{{ $url }}">{{ $title }}</a>
</li>
@endif
</s: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: 'text-gray-900 font-bold'
2: 'text-gray-800 ml-3'
3: 'text-gray-500 ml-6 text-sm'
---
<ul class="nav">
{{ nav }}
<li>
<span class="{{ view:nav_classes[depth] }}">
{{ title }}
</span>
{{ if children }}
<ul class="{{ depth == 1 ?= 'mb-4' }}">
{{ *recursive children* }}
</ul>
{{ /if }}
</li>
{{ /nav }}
</ul>
<ul class="nav">
<s:nav>
<li>
<span @class([
'text-gray-900 font-bold'=> $depth == 1,
'text-gray-800 ml-3'=> $depth == 2,
'text-gray-500 ml-6 text-sm'=> $depth == 3,
])>{{ $title }}</span>
@if (count($children) > 0)
<ul @class([
'mb-4' => $depth == 1
])>
@recursive_children
</ul>
@endif
</li>
</s:nav>
</ul>