开发者

Freemarker Pagination - or just general algorithm for clicking through pages

开发者 https://www.devze.com 2023-03-13 15:27 出处:网络
p - is request parameter where the page number is given by user <#assign totalPages =searchResult.getTotalPages()>
 p - is request parameter where the page number is given by user

<#assign totalPages =searchResult.getTotalPages()>
<#assign lastPage = 0>

<#list totalPages as curPage>
    <#if p=curPage开发者_如何转开发>
         <a href="#" class="selected">${p}</a>
         <#assign lastPage = curPage?number>
    <#else>
         <a href="/search.html?q=${q?html}&amp;p=${curPage}">${curPage}</a>
    </#if>
</#list>

This will print links like this

1 2 3 4 5 6 7 8 9 10 11 - and the list keeps going to the last page lets say 100

What I would like to accomplish is these cases (number in <x> is the p - page selected by user):

Case A: 
1 <2> 3 4 5 ... 100

Case B:
1 ... 11 12 <13> 14 15 ... 100

Case C:
1 ... <96> 97 98 99 100

Any ideas on how to do this in the above freemarker code? Pseudo code is fine too.


Here are two helper functions max and min and a macro I called pages:

<#function max x y>
    <#if (x<y)><#return y><#else><#return x></#if>
</#function>
<#function min x y>
    <#if (x<y)><#return x><#else><#return y></#if>
</#function>
<#macro pages totalPages p>
    <#assign size = totalPages?size>
    <#if (p<=5)> <#-- p among first 5 pages -->
        <#assign interval = 1..(min(5,size))>
    <#elseif ((size-p)<5)> <#-- p among last 5 pages -->
        <#assign interval = (max(1,(size-4)))..size >
    <#else>
        <#assign interval = (p-2)..(p+2)>
    </#if>
    <#if !(interval?seq_contains(1))>
     1 ... <#rt>
    </#if>
    <#list interval as page>
        <#if page=p>
         <${page}> <#t>
        <#else>
         ${page} <#t>
        </#if>
    </#list>
    <#if !(interval?seq_contains(size))>
     ... ${size}<#lt>
    </#if>
</#macro>

This macro produces, when invoked with a sequence of page numbers and the current page, e.g.

<@pages 1..100 2 />
<@pages 1..100 13 />
<@pages 1..100 96 />
<@pages 1..3 2 />

the following output (removed some whitespaces):

1 <2> 3 4 5 ... 100
1 ... 11 12 <13> 14 15 ... 100
1 ... <96> 97 98 99 100 
1 <2> 3 


I think it would be better correct

<#if (p<=5)> <#-- p among first 5 pages -->
    <#assign interval = 1..(min(5,size))>
<#elseif ((size-p)<5)> <#-- p among last 5 pages -->
    <#assign interval = (max(1,(size-4)))..size >

to

<#if (p<=4)> <#-- p among first 5 pages -->
    <#assign interval = 1..(min(5,size))>
<#elseif ((size-p)<4)> <#-- p among last 5 pages -->
    <#assign interval = (max(1,(size-4)))..size >

(just correct 5 -> 4)

Because first code shows weird result in some situation like <@pages 1...12 5>
My expectation was 1 ... 3 4 <5> 6 7 ... 12 but it showed
1 2 3 4 <5> ... 12 which means if current page is 5, can't get to next page.
Second one works correctly as I expected.

0

精彩评论

暂无评论...
验证码 换一张
取 消