miercuri, 11 februarie 2015

Exemplifying <c:if> versus <ui:fragment>

You can consider this post as a "comment" to this question.

A common scenario is to render a table data based on a <c:if> condition, as follows:

<h:dataTable value="#{playersBean.dataArrayList}" var="t">
 <h:column>
  <c:if test="#{t.age gt 26}">
   <h:outputText value="#{t.player}, #{t.age}"/>
  </c:if>
 </h:column>
</h:dataTable>

Well, the result will not be as expected. The problem is that <c:if> is a tag handler; therefore, it is efficiently reflected when the tree is built. A perfect workaround will be to replace <c:if> with the <ui:fragment> tag, which is a component handler. The rendered attribute of <ui:fragment> can successfully replace the <c:if> test using the following code:

<h:dataTable value="#{playersBean.dataArrayList}" var="t">
 <h:column>
  <ui:fragment rendered="#{t.age gt 26}">
   <h:outputText value="#{t.player}, #{t.age}"/>
  </ui:fragment>
 </h:column>
</h:dataTable>

Alternatively, in an even simpler way, use the rendered attribute of <h:outputText>; this approach is particular to this example:

<h:dataTable value="#{playersBean.dataArrayList}" var="t">
 <h:column>
  <h:outputText value="#{t.player}, #{t.age}" rendered="#{t.age gt 26}"/>
 </h:column>
</h:dataTable>

Instead, even cooler, using a lambda expression (EL 3.0), you can write the following code:

<h:dataTable value="#{(playersBean.dataArrayList.stream().filter((p)->p.age gt 26 )).toList()}" var="t">
 <h:column>
  <h:outputText value="#{t.player}, #{t.age}"/>
 </h:column>
</h:dataTable>

Is very possible that lambda expression can help you to easily choose when and what to render.

Niciun comentariu:

Trimiteți un comentariu