Custom Collection Navigation

I have my blog setup so that it has two custom collections, categories and authors like so:

  blog.custom_collections = {
    category: {
      link: '/categories/{category}.html',
      template: '/archive.html'
    },
    author: {
      link: '/authors/{author}.html',
      template: '/archive.html'
    }
  }

Is there a way I can loop through all of my categories and display those in a navigation so I can link to each one? I’m having trouble finding where I can get the list of categories or authors at in order to build this nav.

Thanks!

I’m not sure if this is 100% the best way to do this or not, but I figured out a way to get it to work in case anyone else had a similar issue:

def build_categories(articles)
    categories = []
    articles.each do |article|
      category = article.metadata[:page]['category']
      unless categories.include? category
        categories.push(category)
      end
    end
    return categories
  end

This helper method assumes my custom_collection is named category. I also pass blog.articles to this helper where I want to generate:

  <nav class="categories">
    <% categories = build_categories(blog.articles) %>
    <ul>
      <% categories.each do |category| %>
        <li>
          <%= link_to category, category_path(category) %>
        </li>
      <% end %>
    </ul>
  </nav> <!-- /categories -->

I’m not sure if this is the best way either, but I’ve updated the example a bit to work with Middleman 4. Define a custom collection and a helper method for categories or whatever you would like to name the method. This goes into your config.rb file.

blog.custom_collections = {
    category: {
      link: '/categories/{category}',
      template: '/category.html'
    }
 }

helpers do
    def categories(articles)
      categories = []
      articles.each do |article|
        category = article.data.category
        unless categories.include? category
          categories.push(category)
        end
      end
      return categories.sort
    end
end

Notice that I’m using

category = article.data.category

And then a slight update to the navigation, which for me is in a partial named _header.rb.

<nav role="navigation">
  <% categories = categories(blog.articles) %>
    <ul>
      <% categories.each do |category| %>
        <li>
          <%= link_to "#{category}", category_path(category) %>
        </li>
      <% end %>
    </ul>
</nav>

I just interpolate the value

<%= link_to "#{category}", category_path(category) %>