Fork me on GitHub

Simple pagination algorithm

Mostly inspired from: Algorithm / pseudo-code to create paging links?.

Beware, dirty Scala code.

@(totalPages: Int, currentPage: Int, term: String, filter: Option[String])

@ellipsis = { <li class="ellipsis">...</li> }
@paginationNumber(active: Boolean, route: String, label: String) = {
    <li><a class='button small number @("active".when(active))' href='@route'>@label</a></li>
}

@if(totalPages > 1) {
    <ul>

    @if(currentPage > 1) {
        @paginationNumber(false, routes.Search.index(term, currentPage - 1, filter).toString, "<")
    }

    @paginationNumber((currentPage == 1), routes.Search.index(term, 1, filter).toString, "1")

    @if(currentPage > 2) {
        @if(currentPage > 3) {
            @if(currentPage == 4) {
                @paginationNumber(false, routes.Search.index(term, 2, filter).toString, "2")
            } else {
                @ellipsis
            }
        }

        @if(currentPage == totalPages && totalPages > 3) {
            @paginationNumber(false, routes.Search.index(term, currentPage - 2, filter).toString, (currentPage - 2).toString)
        }

        @paginationNumber(false, routes.Search.index(term, currentPage - 1, filter).toString, (currentPage - 1).toString)
    }

    @if(currentPage != 1 && currentPage != totalPages) {
        @paginationNumber(true, routes.Search.index(term, currentPage, filter).toString, (currentPage).toString)
    }

    @if(currentPage < totalPages - 1) {
        @paginationNumber(false, routes.Search.index(term, currentPage + 1, filter).toString, (currentPage + 1).toString)

        @if(currentPage == 1 && totalPages > 3) {
            @paginationNumber(false, routes.Search.index(term, currentPage + 2, filter).toString, (currentPage + 2).toString)
        }

        @if(currentPage < totalPages - 2) {
            @if(currentPage == totalPages - 3) {
                @paginationNumber(false, routes.Search.index(term, 2, filter).toString, (totalPages - 1).toString)
            } else {
                @ellipsis
            } }
    }

    @paginationNumber((currentPage==totalPages), routes.Search.index(term, totalPages, filter).toString, (totalPages).toString)

    @if(currentPage < totalPages) {
        @paginationNumber(false, routes.Search.index(term, currentPage + 1, filter).toString, ">")
    }

    </ul>
}
Tags: pagination