How to paginate your data ?

Let say you have created your own dataset, then you added a lot of entries on it. It's time to display your data with pagination. In the exemple below, our datatype is posts.

Your AQL request

LET per_page = 10

LET posts = (
  FOR post IN datasets
    FILTER post.type == "posts" AND post.online == true
    SORT post.published_at DESC
    LIMIT (@page - 1) * per_page, per_page
    RETURN post
)

LET post_count = LENGTH(
  FOR post IN datasets
    FILTER post.type == "posts" AND post.online == true
    RETURN 1
)

RETURN { posts, post_count, page: @page, per_page, pages: post_count / per_page }

Notice that @page is special. It will fallback to one if not provided in your URL. So here in this sample /fr/-/home equals /fr/-/home/page/1

Your partials

First define your posts page

<% for k, item in pairs(dataset.results[1].posts) do %>
  <article>
    <h1><%= item.title %></h1>
    <div><%- item.description %></div>
  </article>
<% end %>

{{ partial | pagination | use_params | current_page#<%= dataset.results[1].page %>#pages#<%= dataset.results[1].pages %> }}

And then create a pagination partial with the content below

<% -- pagination %>
<% local page = 0 %>
<% while page < tonumber(dataset._params.pages) do %>
  <% page = page + 1 %>
  <% if page == tonumber(dataset._params.current_page) then %>
    <%= page %>
  <% else %>
    <a href="/en/-/home/page/<%= page %>"><%= page %></a>
  <% end %>
<% end %>
<% -- end pagination %>

You'll be able then to re-use this partial for any new pagination. It will be then easy and fast to update your pagination on the CMS.

Don't forget to create a helper!

Once your AQL & your partial are defined, create an helper which will be included like that in your pages : 

{{ helper | posts }}

Leave a comment