问题
I want to highlight a row when the value of rating is less than or equal to 2
. I am not able to use the <s:if>
to get my result. Please tell me how to put condition in my JSP page.
<table>
<s:iterator value="fb" status="abc">
<s:if test="#abc.rating==2">
<td style="background: #CCCCCC">
</s:if>
<tr>
<td><s:property value="cid"/></td>
<td><s:property value="cname"/></td>
<td><s:property value="rating"/></td>
<td><s:property value="likes"/></td>
<td><s:property value="dislikes"/></td>
<td><s:property value="suggestion"/></td>
</tr>
</s:iterator>
</table>
回答1:
Suppose rating
is a property of the object being iterated. Then inside the iterator tag you can access it by property name.
<s:if test="rating==2">
<s:set var="myStyle" value="'background: #CCCCCC'"/>
</s:if>
<s:else>
<s:set var="myStyle" value="'background: #FFFFFF'"/>
</s:else>
then use HTML style
attribute
<td style="<s:property value='#myStyle'/>">
回答2:
There are several ways:
property name:
<s:iterator value="mySource"> <s:if test="rating==2">
var
alias reference:<s:iterator value="mySource" var="myVar"> <s:if test="#myVar.rating==2">
IteratorStatus index:
<s:iterator value="mySource" status="myStat"> <s:if test="mySource[%{#myStat.index}].rating==2">
top
reference:<s:iterator value="mySource"> <s:if test="top.rating==2">
回答3:
You can use EL (expression language) like this
<td style="background: ${abc.rating<=2 ? '#CCCCCC' : ''}">
or you can define bean variable
<logic:lessEqual value="2" name="abc" property="rating">
<bean:define id="colorTd" value="#CCCCCC"/>
</logic:lessEqual>
<td style="background: ${colorTd}">
回答4:
you have to use test="%{abc.rating==2}" like this instead of test="#abc.rating==2"
<table>
<s:iterator value="fb" status="abc">
<s:if test="%{abc.rating==2}">
<td style="background: #CCCCCC">
</s:if>
<tr>
<td><s:property value="cid"/></td>
<td><s:property value="cname"/></td>
<td><s:property value="rating"/></td>
<td><s:property value="likes"/></td>
<td><s:property value="dislikes"/></td>
<td><s:property value="suggestion"/></td>
</tr>
</s:iterator>
</table>
来源:https://stackoverflow.com/questions/21064377/how-to-add-a-condition-in-struts-iterator-tag