Issue getting next post url

Hi,

I have a blog page and children of this page which are posts of my blog feed.
On my blog page I manage to call and display all the posts.

When I’m on a specific post, I would like to get the next post url. But I don’t manage to display it so far.

Here’s the code I have in the end of my single post template :

{% set collection = page.collection() %}
		
{% if not collection.isFirst(page.path) %}
    <a class="nav nav-prev" href="{{ collection.nextSibling(page.path).url }}"> prev </a>
{% endif %}

{% if not collection.isLast(page.path) %}
    <a class="nav nav-next" href="{{ collection.prevSibling(page.path).url }}"> next </a>
{% endif %}

Thank you very much for your help

@Michael Did you have a look at the skeleton Blog Site? Always handy to have a working example at hand…

If you are on a single blog item, the collection of the page is empty… Therefor when I use your code, ‘previous’ and ‘next’ are always the current page.

Looking at the sourcecode of Page, the methods isFirst(), isLast(), nextSibling() and prevSibling() use $this->parent()->collection(), which is the collection of the main blog page.

This means you can fix the issue by using:

{% set collection = page.parent.collection() %}

Or use the code used by Quarks single page template blog-item.html.twig, which looks simpler if you would ask me:

{% if not page.isLast %}
   <a class="btn" href="{{ page.prevSibling.url }}"><i class="fa fa-angle-left"></i> {{ 'BLOG.ITEM.PREV_POST'|t }}</a>
{% endif %}

{% if not page.isFirst %}
   <a class="btn" href="{{ page.nextSibling.url }}">{{ 'BLOG.ITEM.NEXT_POST'|t }} <i class="fa fa-angle-right"></i></a>
{% endif %}
1 Like

Thank you for your answer.

I was missing something important : my single page template didn’t call the blog-item.html.twig part. As soon as I added it, I was able to get urls of next and previous posts.

The order of my posts wasn’t good so I went to the back office > blog and changed the “order by” value from “time” to “folder”.

Since my projects are not real posts, I wanted to display the url of the first project when I’m on the last one of the list. To do this I used the code you provide me :

{% set collection = page.parent.collection() %}

And get the first url doing this :

{% if page.isLast %}
    <a href="{{ collection.first.url }}">next project</a>
{% endif %}

Thank you for your help, this works perfectly !