Buffalo already ships with very cool pagination support, more than that it even uses the pagination when we generate resources, which is awesome.
I’ve been working lately in a project that uses that pagination (again thanks to the buffalo team), but this app also has a page indicator on the left side, as the following image shows:
Yes, i’m talking about the section that says “Displaying 1 - 25 of 120 Policies” (design typo there).
So my first thought was computing those variables on the action and then passing these to the view, where i would use them to build my “page indicator” section.
My action was turning very ugly, until i realized most (not to say all) that i needed was already contained in the pagination context variable set in my action:
q := tx.PaginateFromParams(c.Params())
…
c.Set("pagination", q.Paginator)
Which is an instance of pops paginator! wow! i already had:
- Page
- PerPage
- Offset
- TotalEntriesSize
- CurrentEntriesSize
With that in hand building my page indicator was not very hard, but wanted to share my _page-indicator.html partial just so if anyone needs to do something similar this could be a good starting point.
<div class="pagination-label">
<span class="opacity">Displaying <%= pagination.Offset + 1 %> - <%= pagination.Offset + pagination.CurrentEntriesSize %> of <%= pagination.TotalEntriesSize %> <%= plural %></span>
<i class="per-page-separator">|</i>
<span class="per-page-<%= perPage(per_page) %>">
<a href="<%= basePath %>?per_page=25"><i class="opacity per-page-25-number per-page-option">25</i></a>
<a href="<%= basePath %>?per_page=50"><i class="opacity per-page-50-number per-page-option">50</i></a>
<a href="<%= basePath %>?per_page=100"><i class="opacity per-page-100-number per-page-option"> 100</i></a>
<i class="opacity"><%= plural %> per page.</i>
</span>
</div>
The way i use this partial from my table templates is:
<%= partial("partials/page-indicator.html", {plural: "Cats", basePath: catsPath({humanSlug: currentHuman.Slug})}) %>
As i’ve said it was very easy with the help of the Paginator that the Buffalo team created for us, hope this helps you if you’re needing to create a page indicator in your app.