Search code examples
htmlpython-2.7paginationcherrypymako

How to do pagination in python mako


I've just started playing around with python to produce web pages. At the moment I am using Mako and CherryPy to create a local server to test anything I write.

I have added a search page for my database, and it could produce any number of results, from 0 to many, so the best way to display is through pagination. I had a quick look online and the only help I can find is this webpage: http://makoframework.com/docs/3.6/learn-more:pagination

The problem is I do not understand what it is showing, so far I have only been using Mako to input variables into the html with the ${variable} notation.

I was hoping someone more experienced could show me and example and explain how and what this does as I cannot find any examples online.

Thank you in advance!


Solution

  • First off, I hope that we both know that your example link leads to the PHP framework site with the same name, Mako.

    For pagination to work you need to implement two methods per entity (or table for simplicity). In simple case, first is count() that returns number of entries, and second is list(page, itemsPerPage) that returns entries for given page.

    Then you need to decide what pagination style you prefer. There are several common styles. E.g. sliding style looks like this:

        [1]  2   3   4  » →
    ← «  1  [2]  3   4  » →
    ← «  2  [3]  4   5  » →
    ← «  3  [4]  5   6  » →
    ← «  4  [5]  6   7  » →
    ← «  4   5  [6]  7  » →
    ← «  4   5   6  [7]
    

    As you've seen in the template snippet at the page you've linked, a pagination template expects several values, e.g. current page, sibling pages, first page, last page, etc. So you need to calculate these values having entry total number of entries, current page, number of entries per page and pagination style. The implementation is quite simple math.

    At the time when I needed such simple page calculation I didn't find one at the Cheese Shop. There were only complicated things that tried to do many things by the way, which I didn't ask. So I wrote PageCalc, which does such simple calcualtion for couple of pagination styles. There's also CherryPy example app which uses Jina2, though it's easy to switch it to Mako if you would like to.