Jekyll select current page url and change its class

HtmlJekyll

Html Problem Overview


I've been using Jekyll for a static site (so that its easy to maintain), and have been stuck at the following feature :

This is my link bar :

<ul id="links">
	<li class="first"><a class="active" href="/">Home</a></li>
	<li><a href="./associate.html">Associate With Us</a></li>
	<li><a href="./media.html">Media</a></li>
	<li><a href="./clients.html">Clients</a></li>
	<li class="last"><a  href="./contact.html">Contact Us</a></li>
</ul>		

The active class handles the coloring. What I want is this class be applied by jekyll depending on some variable set using liquid/YAML.

Is there some easy way to go about this?

Since the bar is common to all the pages, it is now in the default layout. I could go around by using Javascript to detect the url, and do the highlighting but was wondering if there was any way of doing this in Jekyll.

Html Solutions


Solution 1 - Html

I do this in two pages I have set up in Jekyll.

The first thing I do is creating an entry inside _config.yml with the information of all the pages:

# this goes inside _config.yml. Change as required
navigation:
- text: What we do
  url: /en/what-we-do/
- text: Who we are
  url: /en/who-we-are/
- text: Projects
  url: /en/projects/
  layout: project
- text: Blog
  url: /en/blog/
  layout: post

Then, on my main layout, I use that information to generate the navigation links. On each link, I compare the url of the link with the url of the current page. If they are equal, the page is active. Otherwise, they are not.

There's a couple special cases: all blog posts must highlight the "blog" link, and the front pages (English and Spanish) must not present the nav bar. For both cases, I rely on the fact that blog posts and front pages have specific layouts (notice that the "Blog" and "Project" links on the yaml have an extra parameter called "layout")

The navigation code is generated like this:

{% unless page.layout == 'front' %}
  <ul class="navigation">
    {% for link in site.navigation %}
      {% assign current = nil %}
      {% if page.url == link.url or page.layout == link.layout %}
        {% assign current = 'current' %}
      {% endif %}

      <li class="{% if forloop.first %}first{% endif %} {{ current }} {% if forloop.last %}last{% endif %}">
        <a class="{{ current }}" href="{{ link.url }}">{{ link.text }}</a>
      </li>
    {% endfor %}
  </ul>
{% endunless %}

I still have to remember adding an entry to _config.yaml every time I add a new page, and then restart Jekyll, but it happens very infrequently now.

I think the navigation yaml could go inside an _include called "navigation" or something similar, but I haven't tried using yaml inside those so I don't know whether it will work. In my case, since I've got a multi-lingual site, it's easier to have everything inside config (missing translations are easier to spot)

I hope this helps.

Solution 2 - Html

As a further extension on the work of the other, here is a way to make it work without soggy index.html showing on all your beautiful URLs:

---
navigation:
 - text: Home
   url: /
 - text: Blah
   url: /blah/
---
{% assign url = page.url|remove:'index.html' %}
{% for link in page.navigation %}
<li {% if url == link.url %}class="active"{% endif %}>
	<a href="{{link.url}}" title="{{link.title}}">{{link.text}}</a>
</li>
{% endfor %}

The gold is in the assign statement which gets the page URL (which naturally includes the index.html and then strips it off to match the page.navigation pretty URLs.

Solution 3 - Html

This may be a new feature since the question first appeared, but I've discovered this can all be done in one file:

  1. define the navigation as a variable in the yaml header
  2. loop over the variable using liquid

So in my _layouts/base.html I have:

---
navigation:
- text: Home
  url: /index.html
- text: Travel
  title: Letters home from abroad
  url: /travel.html
---

<ul>
	{% for link in page.navigation %}
	<li {% if page.url == link.url %}class="current"{% endif %}>
       <a href="{{link.url}}" title="{{link.title}}">{{link.text}}</a></li>
	{% endfor %}
</ul>

Which generates this on the Home page:

<ul>
	<li class="current"><a href="/index.html" title="">Home</a></li>
	<li><a href="/travel.html" title="Letters home from abroad">Travel</a></li>
</ul>

And this on the Travel page:

<ul>
	<li><a href="/index.html" title="">Home</a></li>
	<li class="current"><a href="/travel.html" title="Letters home from abroad">Travel</a></li>
</ul>

Solution 4 - Html

I needed something simple, this is what I did.

In my front matter I added a variable called active

e.g.

---
layout: generic
title:  About
active: about
---

I have a navigation include with the following section

	<ul class="nav navbar-nav">
		{% if page.active == "home" %}
			<li class="active"><a href="#">Home</a></li>
		{% else %}
			<li><a href="/">Home</a></li>
		{% endif %}
		{% if page.active == "blog" %}
			<li class="active"><a href="#">Blog</a></li>
		{% else %}
			<li><a href="../blog/">Blog</a></li>
		{% endif %}
		{% if page.active == "about" %}
			<li class="active"><a href="#">About</a></li>
		{% else %}
			<li><a href="../about">About</a></li>
		{% endif %}
	</ul>

This works for me as the amount of links in the navigation are very narrow.

Solution 5 - Html

Same navigation on all pages

After reading all that answers, I came up with a new and easier to maintain solution:

  1. Add {% include nav.html %} to your _layouts/layout.html file

  2. Add a nav.html file to your _includes folder

  3. Add the following content to your nav.html file. It will determine if your link is on the current page and add a class of active as well as remove index.html from your link. It will also work with a subfolder like /repo-name, which is needed for GitHub gh-pages Pages branch.

     <nav>
         <ul class="nav">
         	{% assign url = page.url|remove:'index.html' %}
         	{% for link in site.navigation %}
         		{% assign state = '' %}
         		{% if page.url == link.url %}
         			{% assign state = 'active ' %}
         		{% endif %}
         		<li class="{{ state }}nav-item">
         			<a href="{% if page.url == link.url %}{{ site.baseurl }}{% else %}{{ site.baseurl }}{{ link.url }}{% endif %}" title="{{ link.title }}">{{ link.text }}</a>
         		</li>
         	{% endfor %}
         </ul>
     </nav>
    
  4. Then add the nav link array to your _config.yml file as following. Mind the right indentation, as YAML is pretty picky on that (Jekyll as well).

     navigation:
           - text: Home
             title: Back to home page
             url: /index.html
           - text: Intro
             title: An introduction to the project
             url: /intro.html 
           - text: etc.
             title: ...
             url: /foo.html 
    

Assuming that the link to your "Home"-page (index.html) is the first array part inside the _config.htmls navigation array, you can use the following snippet to show the navigation to the different pages on the main/home page and a link back to the home page on all other pages:

<nav>
	<ul class="grid">
		{% assign url = page.url | remove:'/index.html' %}
		{% assign home = site.navigation.first %}
		{% if url == empty %}
			{% for link in site.navigation %}
				{% assign state = '' %}
				{% if page.url == link.url %}
					{% assign state = 'active ' %}
				{% endif %}
				{% if home.url != link.url %}
					<li class="{{ state }}nav-item">
						<a href="{% if page.url == link.url %}{{ site.baseurl }}{% else %}{{ site.baseurl }}{{ link.url }}{% endif %}" title="{{ link.title }}">{{ link.text }}</a>
					</li>
				{% endif %}
			{% endfor %}
		{% else %}
			<li class="nav-item active">
				<a href="{{ home.url }}" title="{{ home.title }}">{{ home.text }}</a>
			</li>
		{% endif %}
	</ul>
</nav>

Solution 6 - Html

This works for me (sorry for non-english code):

<nav>
  <a href="/kursevi" {% if page.url == '/kursevi/' %} class="active"{% endif %}>Kursevi</a>
  <a href="/radovi" {% if page.url == '/radovi/' %} class="active"{% endif %}>Radovi</a>
  <a href="/blog" {% if page.url == '/blog/' %} class="active"{% endif %}>Blog</a>
  <a href="/kontakt" {% if page.url == '/kontakt/' %} class="active"{% endif %}>Kontakt</a>
</nav>

Solution 7 - Html

Navigation highlighting logic is the last thing I would do in server side. I'd rather stick with nice, clean and unobtrusive approach using JS/jQuery (if this option works for you).

  1. The elements which need to be highlighted go inside a common layout like this:

     <nav>
       <a id="section1" href="#">Section 1</a>
       <a id="section2" href="#">Section 2</a>
       <a id="section3" href="#">Section 3</a>
     </nav>
    
  2. In your page (or even in nested layouts) you place an element with data-ref="#section1" (in fact, any jQuery selector will work).

  3. Now, include following JS snippet (shown as jQuery, but any framework will do) in <head>:

     $(function() {
       $("[data-ref]").each(function() {
         $($(this).attr("data-ref")).addClass("current");
       });
     });
    

This approach is nice, because it makes no assumptions on underlying architecture, frameworks, languages and template engines.

Update: As some folks pointed out you might want to omit the $(function() { ... }) part which binds the script to DOM ready event — and just push the script down to the bottom of your <body>.

Solution 8 - Html

Adding to the solution of incarnate, the simplest possible line of code with jQuery is this:

    $( "a[href='{{ page.url | remove: "index.html" }}']" ).addClass("current");

Works perfectly for me.

Solution 9 - Html

I took a simple CSS approach. First, add an identifier in the front matter...

---
layout: page
title: Join us
permalink: /join-us/
nav-class: join <-----
---

Add this as a class in <body> and your nav...

<body class="{{ page.nav-class }}">

and

<li class="{{ page.nav-class }}">...</a></li>

Then link these for all pages in CSS, e.g:

.about .about a,
.join .join a,
.contact .contact a {
color: #fff;
}

The main downside being you need to hard code the style rules.

Solution 10 - Html

With Jekyll 3.4.3, this works :

<ul>
    {% for my_page in site.pages %} 
        {% if my_page.title %}
	        <li {% if my_page.url == page.url %} class="active" {% endif %}>
                <a href="{{ my_page.url | relative_url }}">{{ my_page.title | escape }}
                </a>
            </li>
        {% endif %} {% endfor %}
</ul>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNemoView Question on Stackoverflow
Solution 1 - HtmlkikitoView Answer on Stackoverflow
Solution 2 - HtmlOliView Answer on Stackoverflow
Solution 3 - HtmlJohn MeeView Answer on Stackoverflow
Solution 4 - HtmlRobertKennyView Answer on Stackoverflow
Solution 5 - HtmlkaiserView Answer on Stackoverflow
Solution 6 - HtmlDamian PavlicaView Answer on Stackoverflow
Solution 7 - HtmlBorisOkunskiyView Answer on Stackoverflow
Solution 8 - HtmlbitconquerView Answer on Stackoverflow
Solution 9 - HtmlReg TView Answer on Stackoverflow
Solution 10 - HtmlJack MorrisView Answer on Stackoverflow