Creating next and prev links for pages

I’m guessing this is possible but I’m a bit of a noob with Ruby. I have a bunch of html pages and I want to create next/links on each page to link to the next/page in the sitemap hierarchy based on their url. I’m currently listing all the pages as so…

<% pages = sitemap.resources.find_all{|p| p.source_file.match(/.html/)}.sort_by {|p| p.url} %>

    <% pages.each do |p| %> <% if(p.data.title) %>
  • <%= link_to p.data.title, p.url %>
  • <% end %> <% end %>

But how do I find the next/prev page from that list when I’m on the current page to create a simple navigation?

While middleman understands that the sitemap relates to all content, middleman doesn’t intuitively understand how all the content relates to each other.

In order to have the content relate to each other you may need to name the content in someway that you can programmatically loop through it. Perhaps 01.html, 02.html, etc. Or for each piece of content you could put prev: and next: in the frontmatter of the piece of the content then loop through that.

Thanks for the reply, I had a little play around with the sitemap array and I managed to get something working, although this could probably be improved?

<% pages = sitemap.resources.find_all{|p| p.source_file.match(/\.html/)}.sort_by {|p| p.url} %>
    <% pages.each_with_index do |p, index| %>
      <% if p.url == current_page.url %>
        <% next_page = pages[index+1]  %>
        <% prev_page = pages[index-1] %>
        <%= link_to("<span>Prev</span>", prev_page.path) unless index == 1 %>
        <%= link_to("<span>Next</span>", next_page.path) unless index == pages.size - 1 %>
      <% end %>
    <% end %>
1 Like

I made an extension to do this in a way similar to @scottelundgren’s suggestion, where the files are ordered based on their names: https://github.com/bryanbraun/middleman-navtree

It may be a bit more than you need, since it’s designed to build navigation trees (like a menu, or table of contents) as well as handle pagination.

Thanks @bryanbraun your extention is exactly what i was looking for

But now i need some time to refactor my 2 sides projects http://davidl.fr/forge/ and http://guidecss.fr :slight_smile:

Thanks @olliekav this is great.

Is there a way to read a page’s <title> attribute to affect something like this within the generate links?

<a href="/work/page-1.html">Previous: Page Title 1</a>
<a href="/work/page-3.html">Next: Page Title 3</a>

@fartoo You have access to the Page object, so if you are setting page titles in your yml so could just call.

<%= p.data.title %>

@olliekav Thank you!

<span>Prev: #{prev_page.data.title}</span> did the trick!

1 Like