Pagination outside index with Jekyll

How to access other posts and pages outside the index file.

Background *

When I built this site I needed a way to access other pages and posts outside the current, without using AJA* (so I could have automatic linking to the previous and next post in the header).

Solution *

In the array site.posts you can find, and browse through, all the available posts for the entire site.

{% for post in site.posts%}
    {{ post.title }}
{% endfor %}

Knowing this, there's not much more to it than this:

{% assign i = (site.posts | size) %}
    {% for p in site.posts %}
        {% if p.url == page.url %}
            {% assign pageId = i %}
            {% break %}
        {% endif %}

    {% capture i %}{{ i | minus: 1 }}{% endcapture %}
{% endfor %}

What happens here is that we increment a counter for each post in site.posts, and if the url of the current post in the loop matches the url of the current page we know our pages real id.

If you look close enough, you see that we decrement our counter (i). This is because post id 1 belongs to the first ever post, not the last one*.

*We could have just as easily started at 1 and incremented our counter, but that would have forced us to use the reversed filter in the for loop instead.

This post is one in a series of posts on building a site with Jekyll. These are the articles I have written so far, in no particular order: