refrakt/paginate

Pagination helpers for list views.

Usage in a handler

import refrakt/paginate

pub fn index(req: Request, ctx: Context) -> Response {
  let params = paginate.from_request(req)
  let posts = post_repo.list_paginated(ctx.db, params)
  let page = paginate.page(posts, params, total_count)

  post_views.index_view(page)
  |> root_layout.wrap("Posts")
  |> wisp.html_response(200)
}

Usage in a repo

pub fn list_paginated(db, params: paginate.Params) -> List(Post) {
  let offset = paginate.offset(params)
  pog.query("SELECT ... LIMIT $1 OFFSET $2")
  |> pog.parameter(pog.int(params.per_page))
  |> pog.parameter(pog.int(offset))
  ...
}

Types

A paginated result.

pub type Page(item) {
  Page(
    items: List(item),
    page: Int,
    per_page: Int,
    total: Int,
    total_pages: Int,
    has_previous: Bool,
    has_next: Bool,
  )
}

Constructors

  • Page(
      items: List(item),
      page: Int,
      per_page: Int,
      total: Int,
      total_pages: Int,
      has_previous: Bool,
      has_next: Bool,
    )

Pagination parameters.

pub type Params {
  Params(page: Int, per_page: Int)
}

Constructors

  • Params(page: Int, per_page: Int)

Values

pub fn default_params() -> Params

Default pagination: page 1, 20 items per page.

pub fn from_request(
  req: request.Request(wisp.Connection),
) -> Params

Extract pagination params from query string (?page=2&per_page=10).

pub fn offset(params: Params) -> Int

Calculate the SQL OFFSET from pagination params.

pub fn page(
  items: List(item),
  params: Params,
  total: Int,
) -> Page(item)

Build a Page from items, params, and total count.

pub fn page_url(
  base_path: String,
  page_num: Int,
  per_page: Int,
) -> String

Generate a pagination query string for a given page number.

✨ Search Document