Search code examples
jekyllliquid

Jekyll: link next/previous sorted posts within a category


I need to generate two buttons linking to the next and the previous posts from the same category. Posts are sorted with the front-matter order and an integer value.

My solution is still not perfect. I need to exclude the previous button for the first post and the next button for the last post. However, it's not working and I can't understand why. This is my code:

{% capture the_cat %}{{page.categories | first}}{% endcapture %}
{%- assign sorted_posts = site.categories[the_cat] | sort: 'order' -%}

{%- for post in sorted_posts -%}
  {% if post.url == page.url %}
    {% assign post_index0 = forloop.index0 %}
    {% assign post_index1 = forloop.index | plus: 1 %}
  {% endif %}
{%- endfor -%}

{%- for post in sorted_posts -%}
  {% if post_index0 == post.order %}
    {% assign prev_post = post %}
  {% endif %}
  {% if post_index1 == post.order %}
    {% assign next_post = post %}
   {% endif %}
{%- endfor -%}

And finally...

{%- if prev_post != null -%} ... {%- endif -%}
{%- if next_post != null -%} ... {%- endif -%}

The main loop seems correct. In a category with 3 posts sorted, it returns 1, 2, 3. How can I fix it? Could be fixed with only one loop, making the code more efficient? Thanks!

PD: I used this plugin successfully, however this plugin sorts posts by date, not by order.


Solution

  • Finally, I got the solution:

    {%- capture the_cat -%}{{page.categories | first}}{%- endcapture -%}
    {%- assign sorted_posts = site.categories[the_cat] | sort: 'order' -%}
    
    {%- for post in sorted_posts -%}
        {%- if post.url == page.url -%}
    
        {%- assign currIndex = forloop.index0 -%}
        {%- assign prevIndex = currIndex | minus: 1 -%}
        {%- assign nextIndex = currIndex | plus: 1 -%}
        {%- assign articleIndexLength = forloop.length | minus: 1 -%}
    
        {%- if currIndex == articleIndexLength -%}
            {%- assign prev_post = sorted_posts[prevIndex] -%}
        {%- endif -%}
    
        {%- if currIndex < articleIndexLength and currIndex != 0 -%}
            {%- assign prev_post = sorted_posts[prevIndex] -%}
            {%- assign next_post = sorted_posts[nextIndex] -%}
        {%- endif -%}
    
        {%- if currIndex == 0 -%}
            {%- assign next_post = sorted_posts[nextIndex] -%}
        {%- endif -%}
    
        {%- endif -%}
    {%- endfor -%}
    

    I only needed one loop with three conditionals.