How to implement some if-then logic with JSF and Facelets?
Solution 1
To give the both sides (model and view) the benefit, rather make use of an enum
instead of four independent booleans which might after all only lead to maintenance trouble.
public enum Status {
APPROVED, REJECTED, PROGRESS, PENDING;
}
It is not only much easier and cleaner to handle in Java side, but you can also just print it in EL.
<span class="#{bean.status}" />
Solution 2
The JSF approach is typically using the rendered
attribute on the h-tags. Also note that the EL (expression language) is quite expressive in JSF so you can use ?:
in your class expression. E.g.
<span class="status #{report.approved ? 'approved' : report.rejected ? 'rejected' : report.inProgress ? 'progress' : report.pendingHR ? 'pending' : ''}">
Solution 3
Just make cssStatus
a properties in the backing bean that is resolved to the correct CSS class.
public String getCssStatus() {
if( this.status == .... )
return "green";
else
...
}
And then
<span class="status #{report.cssStatus}">#{report.formattedStatus}</span>
AFAIK, this should work.
Roman
Updated on June 04, 2022Comments
-
Roman almost 2 years
I have a bean with field
status
. Depending onstatus
value different css class should be applied to render it.So, I need something like this (very far from real things pseudocode):
if status == "Approved" cssClass = "green" if status == "Rejected" cssClass = "red" <span class="cssClass">Some info</span>
I tried to apply
jstl
but I can't make it work with facelets and jsf (but I heard that it is possible, maybe its truth). Here is the code:<c:choose> <c:when test="#{report.approved}"> <c:set var="statusClass" value="approved"/> </c:when> <c:when test="#{report.rejected}"> <c:set var="statusClass" value="rejected"/> </c:when> <c:when test="#{report.inProgress}"> <c:set var="statusClass" value="progress"/> </c:when> <c:when test="#{report.pendingHR}"> <c:set var="statusClass" value="pending"/> </c:when> </c:choose> <span class="status ${statusClass}">#{report.formattedStatus}</span>
How should it be done with JSF/Facelets?