Elixir Phoenix pagination list using Scrivener

Antonio Caballes
2 min readJul 24, 2020

--

This is a guide on how to create a simpl pagination in Elixir (Phoenix Framework).

Scrivener is a library in hexdocs that would help us on how to simplify our pagination (hexdocs).

Update dependencies & applications

First thing to do make sure to add scrivener_ecto and scrivener_html in our dependencies.

{:scrivener_ecto, “~> 2.0”},
{:scrivener_html, "~> 1.8"}

Once you have added scrivener in our dependencies, go to def application and look for applications || extra_applications and include scrivener_ecto.

 [..., :scrivener_ecto]

Now fetch dependencies. Type this in your terminal but first go to your project directory:

mix deps.get

Update repo

We want to use our Scrivener in our repo module, so we need to update our repo.ex. I set my page size to 4 but the default page size is set to 10.

By this we can use the paginate function in our repo when we query our database.

use Scrivener, page_size: 4

Use scrivener in our controller

Now let’s go to our controller and use the paginate function.

def index(conn, params) do  page = Product 
|> Repo.paginate(params)
render(conn, "index.html", products: page.entries, page: page)
end

Reference: https://hexdocs.pm/scrivener_list/readme.html

Run your application mix phx.server. Then your index page you will see your list is cut to 4 items. (In my case my product list is now 4 items per page)

Pagination buttons

There are two ways to use pagination links or buttons. You can use a normal link or use the pagination_links in scrivener html.

In this tutorial, I will show you the pagination_links. (This generates the HTML links returned by Scrivener.)

You need to paste this code anywhere in your index page. (In my case I place it under my </table> tag).

<%= pagination_links @page %>

You also need to import the Scrivener.HTML in your views. In my case I will import Scrivener.HTML in my product_view.ex.

Run your application…

pagination_links

As you notice, the buttons are dull… You can read the documentation of Scrivener.HTML on how to put layout or styles on pagination_links.

That’s all for now!

--

--