Other than c:if
or c:choose
, are there any better ways to implement conditional rendering of 1 component out of several components. Something like switch case for JSF pages?
The canonical JSF approach for this is using the rendered
attribute. Here are some examples:
<h:someComponent rendered="#{bean.booleanValue}" />
<h:someComponent rendered="#{bean.intValue gt 10}" />
<h:someComponent rendered="#{bean.objectValue eq null}" />
<h:someComponent rendered="#{bean.stringValue ne 'someValue'}" />
<h:someComponent rendered="#{not empty bean.collectionValue}" />
<h:someComponent rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:someComponent rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />
The difference with JSTL tags is that the rendered
attribute is evaluated during view render time, while JSTL tags are executed during view build time. See also JSTL in JSF2 Facelets... makes sense?
So, if the variables which are necessary for evaluating the condition have a narrower scope than the view scope (i.e. request scope), then you should be using rendered
attribute instead. For example, when re-rendering a group of components upon an ajax request. While the JSTL tags could work equally good in this case, they might be evaluated "too early" (i.e. before the action is invoked, which might in turn have changed the conditions) and they would also break the view scope. See also @ViewScoped
breaks in tag handlers.
If the variables necessary for evaluating the condition have a broader scope, e.g. session-wide or application-wide or are been hardcoded in some template client, then JSTL tags are more efficient as they will be evaluated during view build time only and not everytime during view render time. See also How to make a grid of JSF composite component?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With