如何使用JSTL在列中写出对象数组 [英] How to write out an array of objects in columns using JSTL
问题描述
我有一个JSP,我正在其中显示项目列表.项目列表将放置在垂直列中.每行应具有(列表长度)/(总行数),如果有剩余则四舍五入.现在我们正在做两列,但我们希望可以自由更改列数.
I have a JSP that I am displaying a list of items on. The list of items will be placed into vertical columns. Each row should have (length of list)/(total number of rows), rounding up if there is a remainder. Right now we are doing two columns, but we want the freedom to change the number of columns.
我的工作不喜欢scriptlet,那么使用JSTL将列表分成相等的列的最佳方法是什么?
My work doesn't like scriptlets, so what is the best way to divide a list into equal columns using JSTL?
推荐答案
我会给您与Evgeny给出的答案相似的答案,但准确一些.但是我需要做以下假设:
I will give you a similar answer to the one from Evgeny but a bit more accurate. But I need to make the following assumptions:
- 每行的取整值应为(项目数/列数),而不是(列表长度/项目总数),因为该语句您的列将始终有1个项目.
- 您的JSP上下文具有以下属性:
- 值:包含所有元素的集合或数组
- numRows :一个整数值,用于定义分发列表的行数
- Each of your rows should have a rounded value of (number of items / number of columns) instead of (length of list / total number of items) since in that statement your columns will always have 1 item.
- Your JSP context has following attributes:
- values: a collection or array containing all the elements
- numRows: An integer value defining the number of rows to distribute your list
首先,由于您不能使用任何scriptlet,因此需要以下taglib声明:
First of all, since you can not use any scriptlet, you will need the following taglib declarations:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
现在,要构建项目网格,您将编写类似以下内容的内容:
Now, to build your grid of items you will write something similar to this:
<table> <c:forEach begin="0" end="${numRows - 1}" varStatus="i"> <c:set var="rowStart" value="${i.index * numColumns}" /> <tr> <fmt:formatNumber var="numColumns" value="${fn:length(values) / numRows}" maxFractionDigits="0" /> <c:forEach begin="0" end="${numColumns - 1}" varStatus="j"> <c:set var="index" value="${rowStart + j.index}"/> <td> <c:choose> <c:when test="${index lt fn:length(values)}"> <%-- Replace following code with the one needed to display your item --%> <c:out value="${values[index]}" /> </c:when> <c:otherwise> </c:otherwise> </c:choose> </td> </c:forEach> </tr> </c:forEach> </table>
在此示例中,我首先舍入除法的值以计算要呈现的行数(请参见答案不间断空格",这样您的表将是"HTML"正确".
In this example I am first rounding the value of the division to calculate the number of rows to render (see answer How do I round a number in JSTL?). Then the iteration through items to generate rows and columns start almost exactly as Evgeny did. The main difference resides in that you will need to perform an index check before accessing your list and in case your index is out of bounds, just render a "non breaking space" so your table will be "HTML correct".
这篇关于如何使用JSTL在列中写出对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!