gang
gang

Reputation: 1810

Jekyll page navigation

I would like to create a page-navigation in Jekyll i.e. links to the next and previous projects based on an id.

Say I have the following directory structure:

/example.com
    …
    /_posts
    /projects
        /project1
        /project2
            /index.md
        /project3

I add an index to the front matter of each projects index.md:

projects/project1/index.md:

---
layout: project
title: Project1
index: 0
---

projects/project2/index.md:

---
layout: project
title: Project2
index: 1
---

I tried the folowing in _layouts/default.html to simply output the url of the next page

{% for node in site.pages %}
    {% if node.index == page.index | plus:1 %}
        {{ node.url }}
    {% endif %}
{% endfor %}

As a result I just get the url of the current page.

Upvotes: 1

Views: 1398

Answers (1)

gang
gang

Reputation: 1810

The problem with my first approach seemed to be that the plus: 1 filter did not work as expected. It did not increment the page.index but added the string '1'. In order to add the number 1 it is necessary to assign page.index | plus: 1 to a new variable:

{% for node in site.pages %}
    {% assign next = page.index | plus: 1 %}
    {% assign prev = page.index | minus: 1 %}
    {% if prev == node.index %}
        {% assign prevPage = node %}
    {% endif %}
    {% if next == node.index %}
        {% assign nextPage = node %}
    {% endif %}
{% endfor %}

{% if prevPage %}
    <a href="{{ prevPage.url }}">prev: {{prevPage.title}}</a>
{% endif %}

{% if nextPage %}
    <a href="{{ nextPage.url }}">next: {{nextPage.title}}</a>
{% endif %}

To clean thing up a bit, I also removed the code from _layouts/default.html, created a file called project-navigation.html in the _includes folder and only included it in the layout used for projects: _layouts/project.html:

{% include project-navigation.html %}

Also note that this code generates very much whitespace. In order to avoid this, it is necessary to remove all whitespace and linebreaks in the markup, resulting in this ugly piece of code:

{% for node in site.pages %}{% assign next = page.index | plus: 1 %}{% assign prev = page.index | minus: 1 %}{% if prev == node.index %}{% assign prevPage = node %}{% endif %}{% if next == node.index %}{% assign nextPage = node %}{% endif %} {% endfor %}{% if prevPage %}<a href="{{ prevPage.url }}">prev: {{prevPage.title}}</a>{% endif %}{% if nextPage %}<a href="{{ nextPage.url }}">next:{{nextPage.title}}</a>{% endif %}

Upvotes: 1

Related Questions