Search code examples
jekyllliquid

Jekyll: Previous/Next navigation when using custom navigation


The official Jekyll tutorial has an entire section on using a YAML file to define a custom sequence of pages: https://jekyllrb.com/tutorials/navigation/

But it doesn't mention anywhere how one might create previous/next navigation buttons on the pages within that sequence, which is particularly ironic considering that the tutorial itself has them.

I've come up with some Liquid to determine the index of the current page:

{% for item in site.data.encore.docs %}
    {% if item.url != page.url %}
        {{ item.title }}: {{ forloop.index }}
    {% else %}
        <strong> This page index: {{ forloop.index }}</strong>
        {% assign this_page_index = forloop.index %}
        {% break %}
    {% endif %}
{% endfor %}

but getting the index of the previous page via {% decrement this_page_index %} always returns -1 for some reason, and something like {% assign previous = this_page_index - 1 %} isn't valid Liquid. Same goes for trying to get the next page with similar methods.

What's the ideal way to accomplish this? I've searched every way I can think of and not found anything.


Solution

  • You can find the code for Jekyll's own navigation on their tutorials page by sifting through their GitHub repo until you get to their section_nav_tutorials.html, but it appears the way to do it is very close to what you have.

    Liquid doesn't respect you doing math directly, you have to use a filter. For you, you'd use {% assign previous = this_page_index | minus: 1 %}.