Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c:choose with multiple c:when - fall-through switch

If i have this code on my jsf page:

<c:choose>
    <c:when test="${empty example1}">
    </c:when>

    <c:when test="${empty example2}">
    </c:when>

    <c:otherwise>
    </c:otherwise>     
</c:choose>

it will work like java switch statement with case and break - if first when is true, second won't be test, right ?

What should i write to get "switch statement with case but without break" :

when first C:when is true something add to page and when second is true something is add to page too

like image 545
kuba44 Avatar asked Dec 16 '22 04:12

kuba44


1 Answers

You're thus basically looking for a fall-through switch. That isn't possible with <c:choose> as it represents a true if-else.... JSTL does not offer any tags for a fall-through switch.

Your best bet is to use multiple <c:if>s wherein you also check the preceding condition as an or condition.

<c:if test="#{empty example1}">
    ...
</c:if>
<c:if test="#{empty example1 or empty example2}">
    ...
</c:if>
<c:if test="#{empty example1 or empty example2 or empty example3}">
    ...
</c:if>
...

As you're using JSF, an alternative is using component's rendered attribute.

<h:panelGroup rendered="#{empty example1}">
    ...
</h:panelGroup>
<h:panelGroup rendered="#{empty example1 or empty example2}">
    ...
</h:panelGroup>
<h:panelGroup rendered="#{empty example1 or empty example2 or empty example3}">
    ...
</h:panelGroup>
...

The difference is that it's evaluated during view render time instead of during view build time. So if you were for example using this inside a <h:dataTable> based on the currently iterated row, the <c:if> wouldn't have worked the way you'd expect. See also JSTL in JSF2 Facelets... makes sense?

To eliminate the condition checking boilerplate, you could use <c:set> to create new EL variables. This works in both approaches.

<c:set var="show1" value="#{empty example1}" />
<c:set var="show2" value="#{show1 or empty example2}" />
<c:set var="show3" value="#{show2 or empty example3}" />

<h:panelGroup rendered="#{show1}">
    ...
</h:panelGroup>
<h:panelGroup rendered="#{show2}">
    ...
</h:panelGroup>
<h:panelGroup rendered="#{show3}">
    ...
</h:panelGroup>
...
like image 160
BalusC Avatar answered Dec 21 '22 22:12

BalusC