Sorted navigation menu with Jekyll and Liquid

flyx picture flyx · Jan 29, 2012 · Viewed 23.5k times · Source

I'm constructing a static site (no blog) with Jekyll/Liquid. I want it to have an auto-generated navigation menu that lists all existing pages and highlight the current page. The items should be added to the menu in a particular order. Therefore, I define a weight property in the pages' YAML:

---
layout : default
title  : Some title
weight : 5
---

The navigation menu is constructed as follows:

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

This creates links to all existing pages, but they're unsorted, the sort filter seems to be ignored. Obviously, I'm doing something wrong, but I can't figure out what.

Answer

David Jacquel picture David Jacquel · Aug 26, 2014

Since Jekyll 2.2.0 you can sort an array of objects by any object property. You can now do :

{% assign pages = site.pages | sort:"weight"  %}
<ul>
  {% for p in pages %}
    <li>
      <a {% if p.url == page.url %}class="active"{% endif %} href="{{ p.url }}">
        {{ p.title }}
      </a>
    </li>
  {% endfor %}
</ul>

And save a lot of build time compared to @kikito solution.

edit: You MUST assign your sorting property as an integer weight: 10 and not as a string weight: "10".

Assigning sorting properties as string will ends up in a a string sort like "1, 10, 11, 2, 20, ..."