Skip to content

Essential Navigation Snippet

Posted on: Mar 9, 2021 by Stephanie Eckles
🍿 2 min. read

Grab this snippet to quickly add a basic navigation partial that includes highlighting the current page

The following snippet uses Nunjucks and could be added directly in a layout, or created as a layout partial - ex: nav.njk.

First, we set the variable of currentUrl to contain the current page URL, and if it matches the the nav item's URL, we add the appropriate aria to identify it as the current page.

In this example we are looping through the pages collection, which you may need to adjust to match your desired navigation content.


{% set currentUrl %}{{ page.url }}{% endset %}

<nav>
<ul role="list">
<li>
<a {% if currentUrl === '/' %}aria-current="page"{% endif %} href="/">Home</a>
</li>

{% for page in collections.pages %}
<li>
<a
{% if currentUrl === page.url %}aria-current="page"{% endif %}
href="{{ page.url }}">
{{ page.data.title }}
</a>
</li>
{%- endfor %}
</ul>
</nav>

This navigation strategy is in use for my Smol 11ty Starter

Bonus tip: Attach styles to the current item by using the CSS selector [aria-current="page"] to for example bold the current item, or change its color.

For deeper hierarchies and more complex navigation, you may want to use the official plugin:

View more quick tips