Highlight current menu item in Jekyll for my cosmic radiation site

4 min. read

Caution! This article is 9 years old. It may be obsolete or show old techniques. It may also still be relevant, and you may find it useful! So it has been marked as deprecated, just in case.

I decided to share my lab course from back in 2005, when I was teaching undergraduate students about the awesomity of cosmic radiation. As usual, I made a dedicated site for the project at https://cosmicrad.tk.

I had a lot of fun re-designing the lab guide and the old site so that it reminded of a spaceship, and this time I used HTML entities for the equations instead of MathJax. I turned it into a Jekyll site, so I could host it together with the code of the course. It is pretty similar to my other sites in terms of structure, and it includes a menu that highlights an item when it matches the current page.

Check out the portfolio post.

Highlight current menu item

I used a for loop to automatically populate the menu with the site's pages as I did in my Java snippets site. I also used permalinks and a short name for the items, whose value is specified in a Front Matter variable called short.

<ul>{% for p in site.pages %}{% if p.short %}
  <li><a {% if page.url == p.url %}class="selected"{% endif %} href="{{ p.url | prepend: site.baseurl }}">{{ p.short }}</a></li>{% endif %}{% endfor %}

To highlight the current item, I add a CSS class called "selected" if the current page matches the item. To check that, I compare the contents of the page.url liquid variable with the URL of the page of the current loop iteration, like this:

{% if page.url == p.url %}class="selected"{% endif %}

If the two URLs don't match, no class is added to the item.

Layouts folder

It has a default layout and an extra one to use with the 404 error page, where I change the header titles.

Includes folder

The structure is similar to my other pages, but I split the header file in two, to have different site titles for the error page and the rest of the pages.

Error page

For this site I tried the Google Custom Search (which is basically a script that you paste where you want the search form), since I still haven't got the time to fiddle with Jekyll search implementation. For what I've read in the manual, it doesn't look like there is a built-in searching capability. I might have to find the time to read this SO question more carefully.

The book

The PDF lab guide I made for this physics course looked a bit rusty after all these years. It was typeset with LaTeX, but it used all the LaTeX defaults. At that time I didn't care much about good looks XD. I decided to revamp it and that's how my first book-layout design ever made with LaTeX was born. If you are curious about it, I wrote about the process here. The site's code is in the GitHub repo.