如何使用JSF中的仅标准标签(ui:,h:等)重复输出某些内容?换句话说-如何在JSF中执行与下面的PHP代码相当的操作?我想立即利用 ui:repeat
,但它需要集合-我只有数字。
for ($i = 0; $i < 10; $i++) {
echo "<div>content</div>";
}
如果您已经使用JSF 2.3+,则可以使用<ui:repeat>
标签的begin
/end
属性。
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
...
<ui:repeat begin="1" end="10">
<div>content</div>
</ui:repeat>
如果您还没有升级到JSF 2.3,则可以使用<c:forEach>
代替(确实,将JSTL与JSF混用有时会受到批评,但在您的情况下,这不会造成任何影响,因为您似乎想要“静态”创建视图;它不依赖于任何动态变量):
xmlns:c="http://java.sun.com/jsp/jstl/core"
...
<c:forEach begin="1" end="10">
<div>content</div>
</c:forEach>
或者创建一个EL函数来为<ui:repeat>
创建一个虚拟数组:
package com.example.util;
public final class Functions {
private Functions() {
//
}
public static Object[] createArray(int size) {
return new Object[size];
}
}
该标签库注册在/WEB-INF/util.taglib.xml
中:
<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
version="2.0">
<namespace>http://example.com/util/functions</namespace>
<function>
<function-name>createArray</function-name>
<function-class>com.example.util.Functions</function-class>
<function-signature>Object[] createArray(int)</function-signature>
</function>
</facelet-taglib>
并且被使用如下
xmlns:util="http://example.com/util/functions"
...
<ui:repeat value="#{util:createArray(10)}">
<div>content</div>
</ui:repeat>
由于需要一个集合,您可以在后端Bean中创建一个集合(包含与您要输出div的数量相同的元素):
public class MyBean {
private List list = new ArrayList<Integer();
{ ... populate the list with numbers, for example ... }
public List getList() {
return list;
}
...
}
然后:
<ui:repeat value="#{myBean.list}" var="item">
<div>content</div>
</ui:repeat>
..这将输出与list
属性大小相同数量的div。
of:createArray()
和of:createIntegerArray()
函数:https://showcase-omnifaces.rhcloud.com/showcase/functions/Arrays.xhtml - BalusC