Possible to list all blog posts associated with a tag?

I’d like to create a page/article called ‘regions.’ On this page would be an alphabetically listed set of tags, with an alphabetically listed set of links to blog titles that are associated with that tag. I’m using the middleman-blog template and .erb.

This obviously doesn’t work but I’m thinking something like this:


\---
layout: "custom"
scotch_regions:
  - highlands
  - islay
  - lowlands
\---

articles_tags.scotch_regions.each.sort do |article|
link_to article.title article
end

Tag examples would be: lowlands, highlands, islay.
Blog post titles: "Auchentoshan Three Wood, Dalwhinnie 15, Ardmore Traditional Cask, Laugavulin 16, Laphroaig 10.

What would be displayed:

Highlands
Ardmore Traditional Cask
Dalwhinnie 15

Islay
Laphroaig 10
Laugavulin 16

Lowlands
Auchentoshan Three Wood

I’ve read through most of the Middleman documentation and looked at some of the middleman-blog source. I’m just starting to use this platform and know very little Ruby.

First, is what I’m trying to do possible? I don’t want to beat my head in for nothing.
Second, how do I go about this? I’m not sure what variables to use and the exact ruby code.

Any help appreciated.
Thanks,
Kent

Hi Kent. You might be able to do something like this.

<% articles.sort_by(&:name).each do |article| %>
<% if article.data.region == 'highlands' %>
<%= link_to article.title article %>
<% end %>
<% end %>

and so on for the rest of the regions. If there’s a large list of regions this probably isn’t the best approach.

1 Like

Yes, it’s totally possible. I had a similar need but I listed all the tags with a simple count of how many posts were in each tag. Using @dikaio’s example I believe this is what you’re trying to achieve:

<% blog.tags.sort.each do |tag, articles| %>
  <h2>Posts tagged '<%= tag.capitalize %>'</h2>
  <ul>
  <% articles.sort_by(&:title).each do |article| %>
      <li><%= link_to article.title, article %></li>
  <% end %>
  </ul>
<% end %>

Your posts would then have in the front matter

---
layout: custom
tags: highlands, islay, lowlands
----
1 Like

I want to thank both of you! I took a little from each and came up with the code below, which works for my purpose. In the future I’ll probably figure out how to feed an array of selected tags to the block of code, but for now, this should work fine.

Thanks again,
Kent

<h4>Highlands</h4>
<% blog.tags.sort.each do |tag, articles| %>
  <% if (tag == 'highlands') then %>
    <% articles.sort_by(&:title).each do |article| %>
       <li><%= link_to article.title, article %></li>
    <% end %>
  <% end %>
<% end %>