Skip to content

Commit 60c56d6

Browse files
committed
Explain nav tag mechanism
1 parent 83cbcbb commit 60c56d6

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

docs/5.x/reference/twig/tags.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -558,7 +558,10 @@ This tag works identically to the [namespace](filters.md#namespace) filter, exce
558558
This tag helps create a hierarchical navigation menu for entries in a [Structure section](../element-types/entries.md#section-types) or a [Category Group](../element-types/categories.md).
559559

560560
```twig
561-
{% set entries = craft.entries().section('pages').all() %}
561+
{% set entries = craft.entries()
562+
.section('pages')
563+
.orderBy('lft ASC')
564+
.all() %}
562565
563566
<ul id="nav">
564567
{% nav entry in entries %}
@@ -574,6 +577,13 @@ This tag helps create a hierarchical navigation menu for entries in a [Structure
574577
</ul>
575578
```
576579

580+
Note that we are doing two things to ensure the entire tree of pages is displayed correctly:
581+
582+
- The query fetches _all_ elements: we grab everything in the structure in a single, flat array.
583+
- Ordering by `lft ASC`: this ensures that the pages are properly sorted, such that every child appears after its parent.
584+
585+
Craft then takes this one-dimensional array of elements and evaluates the opening and closing template content (fragments on either side of `{% children %}`, within `{% ifchildren %}`) a number of times appropriate to each item’s `level` relative to the last item.
586+
577587
::: tip
578588
The `{% nav %}` tag should _only_ be used in times when you want to show elements in a hierarchical list. If you want to show elements in a flat list, use a [for](https://twig.symfony.com/doc/tags/for.html) tag instead.
579589
:::

0 commit comments

Comments
 (0)