- This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
Viewing 3 posts - 1 through 3 (of 3 total)
- The forum ‘Other’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Based on the example used in this CSS-Tricks article, more specifically my pen, how is it possible to dynamically add an active
class to its link item when the current page is active?
I am guessing there would need to be a conditional if
statement and a macro used. I am just unclear how to implement.
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 %}">
Thanks Atelier. That’s pretty much it!