Skip to content

Instantly share code, notes, and snippets.

@atelierbram
Last active February 26, 2022 05:37
Show Gist options
  • Save atelierbram/f79349bdf3cc3bfb22011d20a2a69351 to your computer and use it in GitHub Desktop.
Save atelierbram/f79349bdf3cc3bfb22011d20a2a69351 to your computer and use it in GitHub Desktop.
Set Active Class on Nav-Menu-Item in Nunjucks

In html/about/index.html:

{% extends "layouts/layout.njk" %}

{% set base_path = "../../" %}
{% set page_title = "about" %} 

In data.json:

{
  "navItems" : [
    {
      "menu_item" : "lab"
    },
    {
      "menu_item" : "about"
    },
    {
      "menu_item" : "contact"
    }
  ]
}

In html/components/nav.njk

<ul class="nav-menu" id="primary-menu">
  {% for item in navItems %}
    <li class="menu-item menu-item-{{ item.menu_item }}{% if page_title == item.menu_item %} menu-item-current{% endif %}"><a href="../{{ item.menu_item | lower | replace(" ", "") }}/">{{ item.menu_item }}</a></li>
  {% endfor %}
</ul> 

HTML output:

<ul class="nav-menu" id="primary-menu">
  <li class="menu-item menu-item-lab"><a href="../lab/">lab</a></li>
  <li class="menu-item menu-item-about menu-item-current"><a href="../about/">about</a></li>
  <li class="menu-item menu-item-contact"><a href="../contact/">contact</a></li>
</ul>
@atelierbram
Copy link
Author

atelierbram commented Apr 29, 2017

Using the comparison operator == here within an if-statement. This works when the values of the two variables page_title (in this example from about/index.html) and menu_item from the for-loop match, ... and because of the way these templates render:

Because assignments outside of blocks in child templates are global and executed before the layout template is evaluated it’s possible to define the active menu item in the child template:

Resource: Highlighting Active Menu Items
Related: Component-Led Design Patterns with Nunjucks & Grunt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment