Prev/Next for items in eleventyNavigation items
khoivan88 opened this issue · 2 comments
khoivan88 commented
Hi, thank you for a very useful plugin. I was wondering of something like Prev/Next button is possible for items that prepared by eleventyNavigation?
Some think like:
{% set previousChapter = collections.chapters | eleventyNavigation | getPreviousCollectionItem(page) %}
{% set nextChapter = collections.chapters | eleventyNavigation | getNextCollectionItem(page) %}
Right now, if I have nested navigation, the Prev/Next code in this section but as you might have guess, the items would not be in the same order.
Thank you very much
aomarks commented
I also ran into this, so I added a filter to flatten the navigation hierarchy, and add prev
and next
properties:
/**
* Flatten a navigation object into an array, and add "next" and "prev"
* properties.
*/
eleventyConfig.addFilter('flattenNavigationAndAddNextPrev', (nav) => {
const flat = [];
const visit = (items) => {
for (const item of items) {
flat.push(item);
visit(item.children);
}
};
visit(nav);
for (let i = 0; i < flat.length; i++) {
const item = flat[i];
item.prev = flat[i - 1];
item.next = flat[i + 1];
}
return flat;
});
Then in my template I did something like this:
{% set flatNavItems = collections.docs | eleventyNavigation | flattenNavigationAndAddNextPrev %}
{% for item in flatNavItems %}
{% if item.url === page.url %}
{% if item.prev %}
<a href="{{ item.prev.url }}">
Previous: {{ item.prev.title }}
</a>
{% endif %}
{% if item.next %}
<a href="{{ item.next.url }}">
Next: {{ item.next.title }}
</a>
{% endif %}
{% endif %}
{% endfor %}
Hope that helps.
khoivan88 commented
Wow, that's cool. Thank you very much for sharing your solution. It has been a while so i don't remember what i did but this would be super helpful for my future project 😃. Thank you