Previous and Next links with a Collections

Through some trail and error I figured out that the filters previous and next only work on pages and posts. Unless I was doing something very wrong, I was trying to use them on a filtered collection and they were not returning the results that I expected. They returned items that should not have even been in my collection. Since I finally got it working the way I wanted to, I thought I would share and see if there was a better way to do all this.

The site.portfolio query is my collection, and I use two sets of filters to subset the collection to a particular category AND sort it by Year in reverse. page.type matches the custom category name so that I am getting previous and next items within the same collection subset.

{% comment %} 
  Previous / Next functions
  Assign variables from the entire portfolio collection
{% endcomment %}
{% assign items_raw = site.portfolio | where: 'type', page.type %}
{% assign items = items_raw | sort: 'year' | reverse %}

{% if items.size > 1 %}
  {% comment %}
    Store the index position of the matching items
  {% endcomment %}
  {% for item in items %}
    {% if item.title == page.title %}
      {% assign item_index = forloop.index %}
      {% break %}
    {% endif %}
  {% endfor %}
  
  {% assign prev_index = item_index | plus: 1 %}
  {% assign next_index = item_index | minus: 1 %}
  
  {% for item in items %}
    {% if forloop.index == prev_index %}
      {% assign prev = item %}
    {% endif %}
    {% if forloop.index == next_index %}
      {% assign next = item %}
      {% break %}
    {% endif %}
  {% endfor %}

  <p>
    {% if prev %}
      <a href="{{ prev.url }}" class="prev" title="{{ prev.title }}">&lt; Older</a>
    {% endif %}
    {% if prev and next %}
      <span> | </span>
    {% endif %}
    {% if next %}
      <a href="{{ next.url }}" class="next" title="{{ next.title }}">Newer &gt;</a>
    {% endif %}
  </p>
{% endif %}

Again, I’m pretty happy with how it is working (seems to be quick and performant on build) but if there is a better way to do this, please chime in.