Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Other DRY Nunjucks navigation Reply To: DRY Nunjucks navigation

#255960
Atelierbram
Participant

There is this repository mentioned in the CSS-Tricks article linked-to called “Bootstrap Patterns” by the author of the article. In this repository you can find a Nunjucks implementation of setting an active class (I did a PR on the repo recently, also concerning this, so it’s still fresh in my memory).

So one can accomplish this using the comparison operator == within an if-statement, no need for a macro here. This works when the values of the two variables page_id and menu_item from the for-loop in match (see also data.json), … 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:

In html/templates/page1.html:

{% set page_id = "Page 1" %}   

In html/components/nav.njk:

  <li class="nav-item {% if page_id == item.menu_item %}active{% endif %}">