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) %}
{% endfor %}
Yes, it is that simple! :)
Check my latest project compector.com where you can post references about your former employers and see what others have said about the future employers. Sign up now and post a reference and share it on twitter or facebook.


Comments
Leave a Response