Skip to content

Instantly share code, notes, and snippets.

@rockavoldy
Created February 20, 2023 21:04
Show Gist options
  • Save rockavoldy/2e02eb89ae06fbf51c334a0abd313ad9 to your computer and use it in GitHub Desktop.
Save rockavoldy/2e02eb89ae06fbf51c334a0abd313ad9 to your computer and use it in GitHub Desktop.

Pagination with Ellipsis

Says you have total pages = 12

  1. Current page = 1
1, 2, 3, ..., 12
  1. Current page = 2
1, 2, 3, 4, ..., 12
  1. Current page = 7
1, ..., 5, 6, 7, 8, 9, ..., 12
  1. Current page = 10
1, ..., 8, 9, 10, 11, 12

Scripts

def get_pager(pcurr, ptotal):
  # says
  # current page = 1, total pages = 12
  # 1, 2, 3, ..., 12
  # current page = 2, total pages = 12
  # 1, 2, 3, 4, ..., 12
  # current page = 6, total pages = 12
  # 1, ..., 5, 6, 7, 8, 9, ..., 12
  # current page = 10, total pages = 12
  # 1, ..., 8, 9, 10, 11, 12

  delta = 2
  left = pcurr - delta
  right = pcurr + delta + 1
  pages = []
  pagesWithEllipsis = []

  for page in range(1, ptotal+1):
      if page == 1 or page == ptotal or (page >= left and page < right):
          pages.append(page)

  ellips = False
  for page in pages:
      if ellips:
          if page - ellips == 2:
              pagesWithEllipsis.append({'url': get_url(ellips + 1), 'num': ellips + 1})
          elif page - ellips != 1:
              pagesWithEllipsis.append({'url': None, 'num': '...'})
      pagesWithEllipsis.append({'url': get_url(page), 'num': page})
      ellips = page

  return pagesWithEllipsis

Source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment