danmofo
7/28/2015 - 1:09 PM

## pagination.py

``````# [1] 2  3  4  5
#  1 [2] 3  4  5
#  1  2 [3] 4  5
#  2  3 [4] 5  6
#  2  3  4 [5] 6
#  2  3  4  5 [6]

# TODO: Change this so it can work for different pagination counts and not the magic #5

def paginate(result_count, start, items_per_page=10):

# If there are less results than items per page, pagination is useless
if result_count <= items_per_page:
print "nope"
print '-----------------------------------'
return

# Items in pagingation (odd # so the "active" control can be in the middle)
items_in_pagination = 5

# Total amount of pages
page_count = get_total_page_count(result_count, items_per_page)

# Page we're currently on
current_page = (start / items_per_page) + 1

# More items than pages
if items_in_pagination > page_count:
pagination_start = 1
pagination_end = page_count + 1;

# Start page e.g. 1 [2] 3 4 5
elif current_page < 3:
pagination_start = 1
pagination_end = items_in_pagination + 1

# End page e.g. 1 2 3 [4] 5
elif current_page + 2 > page_count :
pagination_start = page_count - 4
pagination_end = page_count + 1

# Everything else, e.g. 1 2 [3] 4 5
else:
pagination_start = current_page - 2
pagination_end = current_page + 3

# Main loop
for page in range(pagination_start, pagination_end):
start_count = (page - 1) * items_per_page
if page == current_page:
print "active:", page, "start={}".format(start_count)
else:
print page, "start={}".format(start_count)

print '-----------------------------------'

# Calculate the total possible amount of pages based on the result count
def get_total_page_count(result_count, items_per_page=10):
count = result_count / items_per_page
overflow = result_count % items_per_page

if(overflow > 0):
count += 1

return count

paginate(493, 0)
paginate(493, 10)
paginate(493, 20)
paginate(493, 30)
paginate(493, 460)
paginate(493, 470)
paginate(493, 480)
paginate(493, 490)
paginate(9, 0)
paginate(11, 0)
paginate(11, 10)
paginate(10, 10)``````