4
votes

In a simple Jekyll site, I have a menu looking like this:

<ul class="nav navbar-nav">
    <li {% if page.url=='/' %} class="active"{% endif %}><a href="/">Home</a></li>
    <li {% if page.url=='/page1.html' %} class="active"{% endif %}><a href="/page1.html">Page 1</a></li>
    <li {% if page.url=='/page2.html' %} class="active"{% endif %}><a href="/page2.html">Page 2</a></li>
    <li {% if page.url=='/page3.html' %} class="active"{% endif %}><a href="/page3.html">Page 3</a></li>
</ul>

When I output page.url just before or after this block, it always contains the expected value, i.e. the path of the current page, say '/page2.html'. However, it's always the Home tab that receives the 'active' class, suggesting that that string comparison succeeded and that page.url is equal to '/'. The fact that visiting the Home page results in page.url containing '/index.html' and not '/' adds to the mystery.

I'm new to Jekyll and Liquid, but I can't think of a reason for this behavior. What am I doing wrong?

2

2 Answers

6
votes

This seems crazy, but it appears that the liquid engine requires spaces around the ==. So this should work:

<ul class="nav navbar-nav">
    <li {% if page.url == '/' %} class="active"{% endif %}><a href="/">Home</a></li>
    <li {% if page.url == '/page1.html' %} class="active"{% endif %}><a href="/page1.html">Page 1</a></li>
    <li {% if page.url == '/page2.html' %} class="active"{% endif %}><a href="/page2.html">Page 2</a></li>
    <li {% if page.url == '/page3.html' %} class="active"{% endif %}><a href="/page3.html">Page 3</a></li>
</ul>

I still don't understand why the first if returns true but this should fix your immediate problem.

1
votes

You can try this :

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

If you want to order your pages in the menu you can have a look at Sorted navigation menu with Jekyll and Liquid