问题
I have HTML table in JSF web application. I am generating rows dynamically using <ui:repeat>
. I want a counter for each row. How can I get this? Any help?
Ssimilar to rowKeyVar in rich faces dataTable.
回答1:
Since you are using richfaces, you can do it with its iteration tag (<a4j:repeat>
), which is a bit more appropriate than using <c:forEach>
, and which is like an extension to <ui:repeat>
<table>
<a4j:repeat value="#{bean.list}" var="item" rowKeyVar="idx">
<tr>
<td><h:outputText value="#{idx + 1}" /></td>
<td><h:outputText value="#{item.someProperty}" /></td>
<td><h:outputText value="#{item.otherProperty}" /></td>
</tr>
</a4j:repeat>
</table>
回答2:
As of Facelets 2.0, this is now possible using the varStatus
.
<ui:repeat varStatus="status" var="user" value="#{collection}">
#{status.index}
</ui:repeat>
回答3:
You can't do it nicely with the ui:repeat
, but you can do so with the h:dataTable
. Bind the component to a UIData property in the backing bean. It has a getRowIndex() method which does exactly what you need:
<h:dataTable binding="#{bean.table}" value="#{bean.list}" var="item">
<h:column><h:outputText value="#{bean.table.rowIndex + 1}" /></h:column>
<h:column><h:outputText value="#{item.someProperty}" /></h:column>
<h:column><h:outputText value="#{item.otherProperty}" /></h:column>
</h:dataTable>
Here I am adding 1
to UIData#getRowIndex()
because it is zero-based. You may find the Using datatables article useful to learn more about datatables.
If you actually want a bit more control over the table layout (especially using colspans/rowspans, which are lacking in the real JSF h:dataTable
tag), then an alternative is to use the JSTL c:forEach tag which has a varStatus
attribute which gives you a handle to the loop status.
<table>
<c:forEach items="#{bean.list}" var="item" varStatus="loop">
<tr>
<td><h:outputText value="#{loop.index + 1}" /></td>
<td><h:outputText value="#{item.someProperty}" /></td>
<td><h:outputText value="#{item.otherProperty}" /></td>
</tr>
</c:forEach>
</table>
回答4:
There is no counter for each row in ui:repeat. As BalusC said you can go for h:datatable. Another idea is indirectly you can add a additional index method in bean for each object in the list in serverside and get that in jsf and manipulate it.
回答5:
A bad (or good idea) is using JavaScript to do that trick.
<script>
var numberOfIndex = 0;
</script>
<ui:repeat value="#{modelBean.listUser}" var="item">
<tr>
<td><script>numberOfIndex -=-1;document.write(numberOfIndex);</script></td>
<td>${item.id}</td>
<td>${item.name}</td>
</tr>
</ui:repeat>
来源:https://stackoverflow.com/questions/1979426/row-counter-for-html-table-row