Recently, I was trying to create a two-column table with multiple rows. I needed to iterate over a collection object and display its data in a table with two columns, something like the one shown below:
Value - 1 Value - 2
Value - 3 Value - 4
Value - 5 Value - 6
...
After some web research regarding the use of the rowIndex property and the use of logical tags, I was able to implement the following code, which is at least free from scriptlet tags (although expressions do appear in some places for required logical evaluations):
<! Start iterating the collection object "studentMarkList".
The "studentMarks" object is popped out on every iteration >
<logic:iterate id="studentMarks" name="studentMarkList" indexId="rowIndex">
<! Check if rowIndex is zero, i.e. its the first element>
<bean:define id="mod" value=
"<%= String.valueOf(rowIndex.intValue())%>" />
<logic:equal name="mod" value="0" >
<! if (rowIndex == 0), add the <table> tag >
<table>
</logic:equal>
<! Check if the current element is a multiple of 2 (add a new row) >
<bean:define id="mod" value=
"<%= String.valueOf((rowIndex.intValue())%2)%>" />
<logic:equal name="mod" value="0" >
<! if (rowIndex % 2 == 0), add the <tr> tag >
<tr>
</logic:equal>
<! Write the student information in the column
(this would execute twice before inserting a new row)>
<td>
<bean:write name="studentMarks"
property="studentName"/> -
<bean:write name="studentMarks"
property="studentPercentage"/>
</td>
<! Check if the current element is a multiple of two
(this means row terminates) >
<bean:define id="mod" value="<%=
String.valueOf((rowIndex.intValue())%2)%>" />
<logic:notEqual name="mod" value="0" >
<! if (rowIndex % 2 != 0), add the </tr> tag >
</tr>
</logic:notEqual>
</logic:iterate>