bungrudi
bungrudi

Reputation: 1417

JSF: logic based on iteration index

Pardon me for the title, that's the best my limited brain can came up this late.

So, i have a list of string, something like [abc, def, ghi].

The question: in JSF, how do I iterate the list and create a string that look like this "abc, def, ghi" (notice the commas)?

For those who have the urge to tell me that I'd better use a Java method to concatenate the string, hear this: every member of the list should be rendered as a separate commandLink.

If plain JSF it would look like:

<h:commandLink>abc</h:commandLink>, <h:commandLink>def</h:commandLink>, <h:commandLink>ghi</h:commandLink>

Upvotes: 1

Views: 3387

Answers (1)

BalusC
BalusC

Reputation: 1108822

Assuming that #{bean.items} returns List<String> or String[], in JSF 1.x you can use JSTL c:forEach with varStatus. It gives you a handle to LoopTagStatus which has a isLast() method.

<c:forEach items="#{bean.items}" var="item" varStatus="loop">
    <h:commandLink value="#{item}" /><c:if test="#{!loop.last}">, </c:if>
</c:forEach>

In Facelets as shipped with JSF 2.x, same functionality is available by ui:repeat.

<ui:repeat value="#{bean.items}" var="item" varStatus="loop">
    <h:commandLink value="#{item}" />#{!loop.last ? ', ' : ''}
</ui:repeat>

Upvotes: 8

Related Questions