Search code examples
rubyhamljekyllawestruct

Awestruct navigation: sort pages by category


What I'm trying to print out is a ul of lis, each containing all the pages which have a given tag (set in the metadata)

If not familiar with Awestruct, it's similar to Jekyll and page metadata can be accessed as page.property, pages are in a site object, and can be iterated over with site.pages.each

What I would like to achieve is something which looks like this:

Category
    Page
    Page
Category
    Page
    Page

Here is what I have so far, I've only been able to print the page titles.

- site.pages.each do |page|
            %li
              %a{ :href => page.url}= page.title

Is there a simple solution that I'm missing?


Solution

  • If I’ve undersood what you want, something like this should work:

    %ul
      -site.pages.group_by(&:category).each do |category, pages|
        %li
          = category
          %ul
            -pages.each do |page|
              %li
                %a{href: page.url}= page.title
    

    This uses group_by to create a hash of arrays of pages keyed on the category attribute, and produces a nested list of all the pages in each one.

    This will include all pages, including thoe without a category, so you might want to filter the pages array first with reject:

    -site.pages.reject{|p| p.category.nil?}.group_by(&:category).each do |category, pages|
      ...