Pagination With WebPy
2009-12-29 08:08:03 | 2 Comments
You know that I have been dealing with major frameworks like Django or Ruby on Rails. However I have decided to learn werkzeug and webpy too. Currently learning webpy. A user on freenode #webpy asked how to implement pagination with webpy and here i explain how to do it.
Let's start with the logic first.
- page should be either in the query string or 1.
- perpage option should be set.
- offset will be calculated with ((page - 1) * perpage).
- total page number will be found by (total data count / perpage)
Here's the deal:
class index:
def GET(self):
params = web.input()
page = params.page if hasattr(params, 'page') else 1
perpage = 3
offset = (int(page) - 1) * perpage
posts = db.select("post", order="id DESC", offset=offset, limit=perpage)
postcount = db.query("SELECT COUNT(*) AS count FROM post")[0]
pages = postcount.count / perpage
return render.index(posts=posts, session=session, pages=pages)
I am using Jinja2 as my template engine so here is how I printed the pages:
{% for page in range(pages) %}
<div style="display: inline; padding-left: 5px;"><a href="?page={{ page+1 }}">{{ page+1 }}</a></div>
{% endfor %}
Yes, it is that simple! :)

Comments
If postcount.count = 12 and perpage = 5, then 2 items will not get to the page. Solution: pages = postcount.count / perpage if postcount.count % perpage > 0: pages += 1
Thank you demoriz, let me update the post when I've got some free time. :)
Leave a Response