69

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.

2
  • I just found out: The sort does something. If a site does not provide a weight, it gets written last. But if it does provide one, it is still not ordered according to it, but according to the file name.
    – flyx
    Jan 29, 2012 at 21:53
  • 4
    I believe that the sort filter might only work with output markup (things wrapped in {{ }}, not {% %}). So, it might not work with as a filter on the for loop. My comment is based on this page: github.com/Shopify/liquid/wiki/Liquid-for-Designers and that it says the filters are for output markup.
    – Owen
    Jan 31, 2012 at 14:46

10 Answers 10

75

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, ..."

7
  • 1
    does not work for me (Jekyll 2.4.0). I defined the weight property in the pages as said above, but the sort seems to ignore it.
    – eyettea
    Oct 2, 2014 at 13:51
  • 2
    @eyetea you are right. We need to make an assignment first. I've editer my code and it works on Jekyll 2.4.0. ;-) Oct 2, 2014 at 15:42
  • Thanks for the help. I also edited the code and removed the second sort filter, since it looks like it's not needed anymore.
    – eyettea
    Oct 2, 2014 at 19:11
  • You're right. I've edited it myself because your suggested edit was rejected by 3 users ??? Oct 2, 2014 at 20:48
  • strange, I just deleted the "| sort: weight"... Why would it be rejected? Anyway, problem solved.
    – eyettea
    Oct 3, 2014 at 1:20
36
+50

Your only option seems to be using a double loop.

<ul>
{% for weight in (1..10) %}
  {% for p in site.pages %}
    {% if p.weight == weight %}
      <li>
        <a {% if p.url == page.url %}class="active"{% endif %} href="{{ p.url }}">
          {{ p.title }}
        </a>
      </li>
    {% endif %}
  {% endfor %}
{% endfor %}
</ul>

Ugly as it is, it should work. If you also have pages without a weight, you will have to include an additional internal loop just doing {% unless p.weight %} before/after the current internal one.

5
  • 1
    lol. I guess you can trim that down by compressing everything into one single line of code if that is a concern. Unfortunately liquid doesn't have a {%- %} prefix to collapse empty lines like erb.
    – kikito
    Mar 6, 2012 at 12:09
  • 3
    Just an addition: Replacing (1..10) with (1..site.pages.size) makes this loop as short as possible, and will work regardless of how many pages you have. Thanks for a stupid yet highly clever hack :) Aug 24, 2013 at 16:47
  • @MarkusAmaltheaMagnuson the (1..10) on this code represent possible weights. It could be replaced by (1..MAX_WEIGHT) to make it a bit more clear (and have MAX_WEIGHT defined somewhere else, like in a constants file).
    – kikito
    Aug 29, 2013 at 8:23
  • 1
    This worked for me, except that the "active" class needed to go on the <li> instead of the <a> Apr 5, 2014 at 14:36
  • This is one of the best things about Jekyll/static-generation - "ugly" as it may be, it only runs once which doesn't affect the user experience or server load. Nice solution! Jun 21, 2014 at 1:05
29

Below solution works on Github (doesn't require a plugin):

{% assign sorted_pages = site.pages | sort:"name" %}
{% for node in sorted_pages %}
  <li><a href="{{node.url}}">{{node.title}}</a></li>
{% endfor %}

Above snippet sorts pages by file name (name attribute on Page object is derived from file name). I renamed files to match my desired order: 00-index.md, 01-about.md – and presto! Pages are ordered.

One gotcha is that those number prefixes end up in the URLs, which looks awkward for most pages and is a real problem in with 00-index.html. Permalilnks to the rescue:

---
layout: default
title: News
permalink: "index.html"
---

P.S. I wanted to be clever and add custom attributes just for sorting. Unfortunately custom attributes are not accessible as methods on Page class and thus can't be used for sorting:

{% assign sorted_pages = site.pages | sort:"weight" %} #bummer
6
  • You good sir deserve a medal. I was just about to resort to generating my site locally and pushing the static HTML to GitHub to be able to use plugins to do this.
    – Adam B
    Dec 12, 2013 at 22:11
  • Would this work for sorting by full file path? i.e. {% assign sorted_pages = site.pages | sort:"path" %} and 00-directory/00-file.md would come before 01-anotherDir/00-anotherFile.md
    – brenna
    Apr 11, 2014 at 15:45
  • It does work! Thanks so much! I've been fighting with this for days.
    – brenna
    Apr 11, 2014 at 15:56
  • 2
    Hi @Wojtek sort:"weight" just works for me, fyi. By the way thanks for the excellent solution.
    – destan
    Jun 13, 2014 at 23:36
  • 1
    Sorting by weight does work! See answer below Maybe that was changed in Jekyll.
    – wedi
    Jul 25, 2014 at 0:33
15

I've written a simple Jekyll plugin to solve this issue:

  1. Copy sorted_for.rb from https://gist.github.com/3765912 to _plugins subdirectory of your Jekyll project:

    module Jekyll
      class SortedForTag < Liquid::For
        def render(context)
          sorted_collection = context[@collection_name].dup
          sorted_collection.sort_by! { |i| i.to_liquid[@attributes['sort_by']] }
    
          sorted_collection_name = "#{@collection_name}_sorted".sub('.', '_')
          context[sorted_collection_name] = sorted_collection
          @collection_name = sorted_collection_name
    
          super
        end
    
        def end_tag
          'endsorted_for'
        end
      end
    end
    
    Liquid::Template.register_tag('sorted_for', Jekyll::SortedForTag)
    
  2. Use tag sorted_for instead of for with sort_by:property parameter to sort by given property. You can also add reversed just like the original for.
  3. Don't forget to use different end tag endsorted_for.

In your case the usage look like this:

<ul>
  {% sorted_for p in site.pages sort_by:weight %}
    <li>
      <a {% if p.url == page.url %}class="active"{% endif %} href="{{ p.url }}">
        {{ p.title }}
      </a>
    </li>
  {% endsorted_for %}
</ul>
2
  • 4
    Just a pity that you can't use custom plugins with GitHub pages… :-\ Jun 2, 2013 at 1:06
  • 3
    Nice, thanks for sharing. Just a little addition: in case not all of your items have the specified property, you can alter the sort_by! call to ignore those items: sorted_collection.sort_by! { |i| i.to_liquid[@attributes['sort_by']] || 0 } (replace 0 with infinity if you want it the other way around). Sep 1, 2013 at 22:23
10

The simplest solution would be to prefix the filename of your pages with an index like this:

00-home.html 01-services.html 02-page3.html

Pages are be ordered by filename. However, now you'll have ugly urls.

In your yaml front matter sections you can override the generated url by setting the permalink variable.

For instance:

---
layout: default
permalink: index.html
---
2
  • Nice one! Still a hack, but much simpler than the other answers.
    – flyx
    Sep 20, 2012 at 12:07
  • Be careful with this if you push your site to github pages. For some reason the ordering will be messed up then. See also: github.com/plusjade/jekyll-bootstrap/issues/…
    – Christiaan
    Jan 29, 2013 at 21:38
10

Easy solution:

Assign a sorted array of site.pages first then run a for loop on the array.

Your code will look like:

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

This works in my navbar _include which is simply:

<section id="navbar">
    <nav>
        {% assign tabs = site.pages | sort: 'weight' %}
        {% for p in tabs %}
            <span class="navitem"><a href="{{ p.url }}">{{ p.title }}</a></span>
        {% endfor %}
    </nav>
</section>
3
  • Suddenly this started throwing errors on _post pages: Liquid Exception: comparison of Hash with Hash failed in _posts/...
    – sdmeyers
    Oct 10, 2013 at 13:06
  • This is the cleanest solution; there's just a slight error -- the sort key should be given as a string, i.e. sort: 'weight'. Updated the sample code.
    – lfk
    May 7, 2014 at 8:40
  • The aforementioned issue is mentioned and resolved here. It might take a while before the versions running GitHub pages are updated, though.
    – lfk
    May 8, 2014 at 0:06
5

I've solved this using a generator. The generator iterates over pages, getting the navigation data, sorting it and pushing it back to the site config. From there Liquid can retrieve the data and display it. It also takes care of hiding and showing items.

Consider this page fragment:

---
navigation:
  title: Page name
  weight: 100
  show: true
---
content.

The navigation is rendered with this Liquid fragment:

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

Put the following code in a file in your _plugins folder:

module Jekyll

  class SiteNavigation < Jekyll::Generator
    safe true
    priority :lowest

    def generate(site)

        # First remove all invisible items (default: nil = show in nav)
        sorted = []
        site.pages.each do |page|
          sorted << page if page.data["navigation"]["show"] != false
        end

        # Then sort em according to weight
        sorted = sorted.sort{ |a,b| a.data["navigation"]["weight"] <=> b.data["navigation"]["weight"] } 

        # Debug info.
        puts "Sorted resulting navigation:  (use site.config['sorted_navigation']) "
        sorted.each do |p|
          puts p.inspect 
        end

        # Access this in Liquid using: site.navigation
        site.config["navigation"] = sorted
    end
  end
end

I've spent quite a while figuring this out since I'm quite new to Jekyll and Ruby, so it would be great if anyone can improve on this.

1

I can get the code below works on with Jekyll/Liquid match to your requirement with category:

  • creates links to all existing pages,
  • sorted by weight (works as well on sorting per category),
  • highlight the current page.

On top of them it shows also number of post. All is done without any plug-in.

<ul class="topics">
{% capture tags %}
    {% for tag in site.categories %}
        {{ tag[0] }}
    {% endfor %}
{% endcapture %}
{% assign sortedtags = tags | split:' ' | sort %}
    {% for tag in sortedtags %}
    <li class="topic-header"><b>{{ tag }} ({{ site.categories[tag] | size }} topics)</b>
        <ul class='subnavlist'>
        {% assign posts = site.categories[tag] | sort:"weight" %}
        {% for post in posts %}
            <li class='recipe {% if post.url == page.url %}active{% endif %}'>
            <a href="/{{ site.github.project_title }}{{ post.url }}">{{ post.title }}</a>
            </li>
        {% endfor %}
        </ul>
    </li>
    {% endfor %}
</ul>

Check it on action on our networking page. You may click a post to highlight the navigation, as well a given link to bring you to the source page where their weight is assigned.

0

If you're trying to sort by weight and by tag and limit the number to 10, here's code to do it:

{% assign counter = '0' %}
{% assign pages = site.pages | sort: "weight"  %}
{% for page in pages %}
{% for tag in page.tags %}
{% if tag == "Getting Started" and counter < '9' %}
{% capture counter %}{{ counter | plus:'1' }}{% endcapture %}
<li><a href="{{ page.permalink | prepend: site.baseurl }}">{{page.title}}</a></li>
{% endif %}
{% endfor %}
{% endfor %} 
-1

The solution above by @kikito also worked for me. I just added a few lines to remove pages without weight from the navigation and to get rid of white space:

<nav>
  <ul>
    {% for weight in (1..5) %}
      {% unless p.weight %}
        {% for p in site.pages %}
          {% if p.weight == weight %}
            {% if p.url == page.url %}
              <li>{{ p.title }}</li>
            {% else %}
              <li><a href="{{ p.url }}" title="{{ p.title }}">{{ p.title }}</a></li>
            {% endif %}
          {% endif %}
        {% endfor %}
      {% endunless %}
    {% endfor %}
  </ul>
</nav>
1
  • @WingLeong I didn't do any tests but that's what worked out for me.
    – jupiteror
    Jun 27, 2014 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.