Search and paginate
Using the search and paginate helpers to create dynamic pages.
The variables search and paginate are global functions that allow searching other pages and paginating the result.
Searching pages
The function search.pages() returns an array of pages you can filter and sort. For example, to search pages with the variable category equals to music, use the following code:
<ul>
{{ for page of search.pages("category=music") }}
<li><a href="{{ page.url }}">{{ page.title }}</a></li>
{{ /for }}
</ul>
Each page returned is an object with its data. In this example, we use the title and url to build the list of links to the pages.
The search helper is very powerful and has more interesting features. Go to the Search plugin documentation for more info.
Pagination
In Lume you can create multiple pages using a generator. Pagination uses basically the same concept to create multiple pages using the result of a search.
Let's say we want to paginate some pages in groups of 10 elements. We could do it manually with a generator:
export default function* ({ search }) {
// Select the pages
const pages = search.pages("category=music");
const totalResults = pages.length;
let currentPage = 1;
while (pages.length) {
// Extract the 10 first results
const results = pages.splice(0, 10);
yield {
layout: "layouts/post-list.vto",
url: `/music/page-${currentPage}/`,
results,
pagination: {
currentPage,
totalResults,
},
};
// Increase the page number
++currentPage;
}
}
In this example, we selected all pages to generate a page for each 10 results with the urls /music/page-1/, /music/page-2/, /music/page-3/, etc. The generated pages use the layout layouts/post-list.vto with the variables results, pagination, etc.
The Paginate plugin (enabled by default in Lume), exposes the paginate helper to ease this process. The previous example can be simplified as following:
export const layout = "layouts/post-list.vto";
export default function* ({ search, paginate }) {
const musicPages = search.pages("category=music");
for (const page of paginate(musicPages))) {
yield page;
}
}
Go to the paginate plugin documentation for more info.