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>
Using the comparison operator
==
here within an if-statement. This works when the values of the two variablespage_title
(in this example fromabout/index.html
) andmenu_item
from the for-loop match, ... and because of the way these templates render:Resource: Highlighting Active Menu Items
Related: Component-Led Design Patterns with Nunjucks & Grunt