Search code examples
javajsfjstlfacelets

How to implement some if-then logic with JSF and Facelets?


I have a bean with field status. Depending on status 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?


Solution

  • 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}" />