Question

Grails Paginate tag generates links with max and offset params. Example

/?max=30&offset=0
/?max=30&offset=30

Say we have constant max equals 30.

Is there any possibility to make it generate page numbers instead?

/?page=1
/?page=2
Was it helpful?

Solution 2

This is my solution

In controller:

params.max = 30
if(params.long('page')) {
    params.offset = (params.long('page') - 1) * params.max
}

In tag lib:

static namespace = "my"

private final static Pattern OFFSET_PATTERN = Pattern.compile("offset=(\\d+)");

def paginate = { attrs, body ->
    String str = g.paginate(attrs) // using grails gsp paginate tag
    // make sure we delete max param with & (before or after)
    str = str.replaceAll(/&max=\d+/, '').replaceAll(/max=\d+&/, '')
    while (true) {
        Matcher matcher = OFFSET_PATTERN.matcher(str)
        if (matcher.find()) {
            long pageNum = (matcher.group(1) as long)/params.long('max') + 1
            // replace offset=0 with page=1, offset=30 with page=2, etc
            str = matcher.replaceFirst('page=' + pageNum)
        } else {
            break;
        }
    }
    out << str
}

So we can use my.paginate in our gsp views the same way we use standard grails gsp paginate tag. Looking forward your feedbacks and improvements

OTHER TIPS

You could change the controller itself. Something along the line of:

def myMethod() {
    params.max = 30
    params.offset = (params.max * params.page) - params.max //todo - make sure page is bigger than one :-)
    def listOfItemsYouWantToShow = MyPerfectDomainClass.list(params)
    ....
}

not tested, but should work.

The view tag should be also changed, just like the first comment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top