limit number of iterations in ui:repeat

flybywire picture flybywire · Dec 2, 2013 · Viewed 10.7k times · Source

We have a JSF page that displays a table with query results. We want to show just the top 3 results.

How can this be done using <ui:repeat>?

We can't do this in the business layer, because it is not under our control. We need to cap the results to 3 in view side.

Answer

skuntsel picture skuntsel · Dec 2, 2013

You can follow the way kocko proposes in his answer, but certainly it's quite excessive to iterate through the whole list to output only three components.

The necessity of such verbose approach is dictated by the fact that size attribute of <ui:repeat> component doesn't for some reason allow to specify EL as its value but rather plain integer like 3. See also Jsf ui:repeat size doesn't gets java bean value.

If you know that only 3 values are needed you can use the size attribute:

<ui:repeat var="var" value="#{bean.list}" size="3">
    <h:outputText value="#{var}" />
</ui:repeat>

Alternatively, if you are on EL2.2+ you can get a sublist by calling List#subList(from, to) method:

<ui:repeat var="var" value="#{bean.list.subList(0, (bean.list.size() gt 3) ? 3 : bean.list.size())}">
    <h:outputText value="#{var}" />
</ui:repeat>