I'm looking for a Play Framework pagination example. Please help me with a good reference link.
I searched for it and don't have java code.
I'll provide a Scala solution and you can adjust your code.
You could create a utility class called Paginator
:
package util
case class Paginator[A](items: Seq[A], page: Int, offset: Long, total: Long) {
lazy private val pageSize: Int = 20 // you can adjust to your preference
lazy val prevPage: Option[Int] = Option(page - 1).filter(_ >= 0)
lazy val nextPage: Option[Int] = Option(page + 1).filter(_ => (offset + items.size) < total)
lazy val numberOfPages: Float = if (total % pageSize > 0) { total / pageSize + 1 }
else { total / pageSize }
}
In your controller you will do something like:
def list(currentPage: Int) = Action.async { implicit request =>
val offset: Int = currentPage * resultsPerPage
// Put your logic here to get the `listOfItems` you want to display
// and the number of `totalItems`
// and then return Ok and call your view
Ok(views.html.list(Paginator(listOfItems, currentPage, offset, totalItems)))
}
and finally in your view you will have something like:
@import util.Paginator
@(paginatedList: Paginator[Item])(implicit msg: play.api.i18n.MessagesProvider)
@main(msg.messages("label.list_of_items")) {
<h1>@msg.messages("label.paginated_list")</h1>
@* populate your list here *@
@* and this is your paginator *@
<div class="pagination">
@paginatedList.prevPage.map { page =>
<a href="@link(page)">@msg.messages("label.previous")<a>
}.get
@for(pageNumber <- 1 to paginatedList.numberOfPages.toInt) {
<a href="@routes.Controller.list(pageNumber - 1)">@pageNumber</a>
}
@paginatedList.nextPage.map { page =>
<a href="@link(page)">@msg.messages("label.next")</a>
}.get
</div>
}
I got the original idea from this project and I've expanded on it. You can also improve the paginator by using getOrElse
to provide alternative/disabled links when being on the first/last page, or to disable the current page number etc.
I hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.