DEV Community

Adam Jolicoeur
Adam Jolicoeur

Posted on

Setting active state on navigation with Eleventy

In creating my portfolio site, I wanted to have dynamic elements that would add/remove classes based on the site's structure, as well as the page content. The first step in this was the navigation.

Problem

Setting the active class to be applied when parsing through my collections, and having it only apply to particular a page, was just not working. I tried using various properties such as tag, title, and even the eleventyNavigation plugin.

{% set navPages = collections.all | eleventyNavigation %}
  <div class="navbar-nav col-md-6 justify-content-md-center">
    <a class="navbar-brand col-md-1 me-0 text-center" href="/">
      <img src="{{ "/img/navbar-logo.png" | url }}" alt="Avatar" width="32" height="32">
    </a>
    {%- for entry in navPages %}
    {# <a class="nav-link" href="{{ entry.url }}" alt="{{entry.description}}">{{ entry.title }}</a> #}
    <a class="nav-link {{ 'active' if 'entry.title' in entry.url }}" href="{{ entry.url }}" alt="{{ entry.abbreviation }}">{{ entry.title }}</a>
    {%- endfor %}
  </div>
Enter fullscreen mode Exit fullscreen mode

No matter what I tried, nothing would set the active state of the page to the proper one.

Solution (easy way out)

After stumbling around through various #eleventy guides, I came across various implementations of the <% if %> statement, but none of them ever worked for me. In the end, I decided to simplify my navigation to, instead of using collections, fall back to the tried and true individual <a> for each navigation item. This allowed me to utilize the <% if %> statement to look for a specific location and, if the URL contained that string, apply the active class.

<a class="nav-link {% if '/designs' in page.url %}active{% endif %}" href="/designs" alt="Link to Designs that I have created and worked on.">designs</a>
Enter fullscreen mode Exit fullscreen mode

This now applies the active class to any page that has /designs in the URL. No longer am I reliant on the collections information being read, nor am I having to worry about a page ending up on the wrong place and applying the class incorrectly.

Next steps

Ideally, I would be able to set my site to read through all of the items in my collections and then parse through that information to apply the active class correctly. As I build out my site and want to rely less on manually updating the navigation, this will become paramount (looking at you, breadcrumbs).

Conclusion

If you found this short bit of information helpful, let me know in the comments or by adding a reaction. If you have any suggestions, I'm open to hearing any and all!

View source on GitHub

Top comments (0)