jacosta
jacosta

Reputation: 457

Struts2 conditional check inside iterator

I have a table in a jsp in which i am displaying data from a list, using the s:iterator tag. The list is already sorted by description and I need to be able to display a row in the table above each group of descriptions. For example (imagine this is a table):

Heading1-----
1 Heading1
2 Heading1
3 Heading1
Heading2-----
4 Heading2
5 Heading2
Heading3-----

What i want to do is iterate through the list and compare the current description with the previous description and if they are different, display the current description as a new row.

I tried a few different variations of this - which did not work:

<s:iterator value="myList" status="rowStatus">
<s:if test="{myList[%{#rowStatus.index}].description != myList[%{#rowStatus.index-1}].description}">
     <tr>
          <td colspan="7"><s:text name="description"/></td>
     </tr>
 </s:if>

I feel like i'm very close, but I just can't seem to figure out the proper syntax. What am i missing here??

Thanks in advance!

*j

Upvotes: 3

Views: 3496

Answers (1)

Dave Newton
Dave Newton

Reputation: 160191

The OGNL expression should be the entire "test" attribute:

<s:iterator value="myList" status="rowStatus">
  <s:if test="%{myList[#rowStatus.index].description != myList[#rowStatus.index-1].description}">
    ... etc ...

That said, it seems a lot of noise in the JSP; I'd consider something like this:

<s:iterator value="myList" status="rowStatus">
  <s:if test="%{#cur != description}">
      ... etc ...
  </s:if>
  <s:set var="cur" value="description"/>
</s:iterator>

There are other options, including setting a flag on the Java side.

Upvotes: 4

Related Questions