_k

Current menu item highlight

After searching how to highlight the current menu item in jekyll just to find too complex answers on stackoverflow, i decided to do a quick-tip on this topic.

Consider following markup:

...
{% for page in site.pages %}
  <li>
    <a href="{{ page.url }}">
      {{ page.title }}
    </a>
  </li>
{% endfor %}
...

This loops over all pages and puts them in a list. To put an active class on the current link we need a way to compare the current page to the pages in the loop.

This is where the jekyll page variable comes in. In this variable jekyll stores the page being rendered and all the variables which are set in the front matter. I’m using the title variable to compare my current post to the posts in the loop.

After extending the above code it looks like this.

...
{% for p in site.pages %}
  <li>
    {% assign classes = '' %}
    {% if p.title == page.title %}
      {% assign classes = 'active' %}
    {% endif %}
     
    <a class="{{ classes }}" href="{{ p.url }}">
      {{ p.title }}
    </a>
  </li>
{% endfor %}
...

Alternatively, for an even quicker solution, it’s possible to just compare the pages. Which produces the same results.

...
{% if p == page %}
  {% assign classes = 'active' %}
{% endif %}
...

Quick two minute solution which works quite nice and should be easy extensible.