【发布时间】:2013-08-31 16:46:30
【问题描述】:
我正在使用 Spring + Thymeleaf 开发一个简单的应用程序。在其中一个页面上,我有一个需要分页的项目列表。
理想情况下,我只想将currPageNo(当前页数)和numOfPages(总页数)变量发送到视图,其余的工作将在那里完成(这个是一个演示问题,与业务逻辑无关)。但是,如果最干净的解决方案需要我首先在控制器中进行一些计算,我会接受它作为一个小问题。
我想获取以下形式的页面列表。
<Prev | 1 | ... | 3 | 4 | 5 | 6 | 7 | ... | 15 | Next>
我只能提供以下解决方案。它有效,但我相信您会同意它非常混乱且非常难以阅读。
此外,除了currPageNo 和numOfPages,我还必须向视图发送另外两个变量。理想的解决方案不需要我这样做。
firstPageNo = Math.max(2, currPageNo - 2)
lastPageNo = Math.min(numOfPages - 1, currPageNo + 2)
我的代码的当前版本如下。
<ul>
<li th:if="${currPageNo > 1}">
<a th:href="@{/items.html(pageNo = ${currPageNo - 1})}" href="">< Prev</a>
</li>
<li th:class="${currPageNo == 1} ? 'selected'">
<a th:href="@{/items.html(pageNo = 1)}" th:if="${currPageNo > 1}" href="">1</a>
<span th:if="${currPageNo == 1}">1</span>
</li>
<li th:if="${currPageNo >= 5}">
...
</li>
<li th:each="pageNo : ${#numbers.sequence(firstPageNo, lastPageNo)}" th:class="${currPageNo == pageNo} ? 'selected'">
<a th:href="@{/items.html(pageNo = ${pageNo})}" th:if="${pageNo != currPageNo}" th:text="${pageNo}" href="">2</a>
<span th:if="${pageNo == currPageNo}" th:text="${pageNo}">2</span>
</li>
<li th:if="${currPageNo <= (numOfPages - 4)}">
...
</li>
<li th:class="${currPageNo == numOfPages} ? 'selected'">
<a th:href="@{/items.html(pageNo = ${numOfPages})}" th:if="${currPageNo < numOfPages}" th:text="${numOfPages}" href="">10</a>
<span th:if="${currPageNo == numOfPages}" th:text="${numOfPages}">1</span>
</li>
<li th:if="${currPageNo < numOfPages}">
<a th:href="@{/items.html(pageNo = ${currPageNo + 1})}" href=""> Next ></a>
</li>
</ul>
以下列表总结了我最想摆脱的问题。我知道其中一些是平台固有的,但列表似乎很长而且代码很乱。
- 必须将
firstPageNo和lastPageNo的预计算值从控制器发送到视图。 - 必须在表达式中使用
&lt;而不是<。 - 必须同时使用具有互斥条件的锚点和跨度,以使浏览器不使用当前页面的链接。
我也欢迎任何其他关于如何提高代码质量的建议。
我知道这个问题可能更适合 Code Review 网站,但是,由于 Thymeleaf 似乎是一项用户群很小的技术,我希望在 Stack Overflow 上得到一个合理的答案,它有一个更大的用户群(我相信)。
但是,如果这里真的不欢迎这样的问题,请考虑将其移至正确的站点而不是关闭它,以便我获得所需的建议。
【问题讨论】:
标签: spring pagination thymeleaf