我正在开发一个使用Spring + Thymeleaf的简单应用程序。在其中一页上,我有一份需要分页的项目清单。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
发送到控制器的视图。 - 必须在表达式中使用
<
而不是<
。 - 必须使用具有互斥条件的锚点和跨度,以便浏览器不要为当前页面使用链接。
我也欢迎任何其他有关如何提高代码质量的建议。
我明白,也许这个问题将是一个更适合的代码审查现场,但作为Thymeleaf似乎是一个很小的用户群的技术还没有,我期待一个合理的答案,而在这里堆栈溢出,它有更大的用户群(我相信)。
但是,如果真的不欢迎这样的问题,请考虑将它移到正确的网站而不是关闭它,以便我得到我需要的建议。
请附上一些文字,例如带有代码的解释。 –
不要只是转储代码...并添加一些肉。 – Werner
注意到现在,您必须用'first'和'last'替换'firstPage'和'lastPage'。 – membersound