1

I want to make a navigation sorted by weight on my Jekyll site. I'm using this plugin, but I want to show in navigation only pages with weight, instead of showing pages without weight at the end of the list.

So I changed the plugin like this:

module Jekyll
  class WeightedPagesGenerator < Generator
    safe true
    def generate(site)
      site.pages.each do |page|
        if page.data["weight"] != nil

          site.config['weighted_pages'] = site.pages.sort_by { |a| 
            a.data['weight'] }

        end
      end
    end
  end
end

But I get an error: Generating... /_plugins/sorted_navigation.rb:10:in `sort_by': comparison of NilClass with 2 failed (ArgumentError).

Any idea how to make this work?

jupiteror
  • 1,085
  • 3
  • 24
  • 50
  • try this in your method, site.config['weighted_pages'] = site.pages.sort_by { |a| a.data['weight'].to_i } – Alok Anand Apr 05 '14 at 11:31
  • you can replace this block site.pages.each do |page| if page.data["weight"] != nil site.config['weighted_pages'] = site.pages.sort_by { |a| a.data['weight'] } end end – Alok Anand Apr 05 '14 at 11:33
  • with site.config['weighted_pages'] = site.pages.sort_by { |a| a.data['weight'].to_i } – Alok Anand Apr 05 '14 at 11:33
  • 1
    @AlokAnand, thank you very much. Now it actually doesn't give any error when I generate the site, but I still get pages without weight in my navigation. So I guess now the if statement doesn't work. – jupiteror Apr 06 '14 at 04:55

2 Answers2

1

Since Jekyll 2.2.0 you can sort an array of objects by any object property. Sorting by weight is now possible and far more efficient than older solutions (see https://stackoverflow.com/a/25513956/1548376)

Community
  • 1
  • 1
David Jacquel
  • 51,670
  • 6
  • 121
  • 147
0

I ended up not using this plugin. Instead I use liquid tags from this answer and now my navigation looks like this:

<nav>
  <ul>
    {% for weight in (1..5) %}
      {% unless p.weight %}
        {% for p in site.pages %}
          {% if p.weight == weight %}
            <li><a {% if p.url == page.url %}class="active"{% endif %} href="{{ p.url }}" title="{{ p.title }}">{{ p.title }}</a></li>
          {% endif %}
        {% endfor %}
      {% endunless %}
    {% endfor %}
  </ul>
</nav>
Community
  • 1
  • 1
jupiteror
  • 1,085
  • 3
  • 24
  • 50