How to repeat output of text via simple for loop in Facelets without model?

风流意气都作罢 提交于 2019-12-02 15:53:06

Either use <c:forEach> instead (true, mixing JSTL with JSF is sometimes frowned upon, but this should not harm in your particular case because you seem to want to create the view "statically"; it does not depend on any dynamic variables):

xmlns:c="http://java.sun.com/jsp/jstl/core"
...
<c:forEach begin="1" end="10">
    <div>content</div>
</c:forEach>

Or create an EL function to create a dummy array for <ui:repeat>:

package com.example.util;

public final class Functions {

    private Functions() {
        //
    }

    public static Object[] createArray(int size) {
        return new Object[size];
    }
}

which is registered in /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>

and is been used as follows

xmlns:util="http://example.com/util/functions"
...
<ui:repeat value="#{util:createArray(10)}">
    <div>content</div>
</ui:repeat>

Update: I just posted an enhancement request to add the begin and end attributes to <ui:repeat>: http://java.net/jira/browse/JAVASERVERFACES-2240

Update 2: I have personally implemented it for JSF 2.3 as per https://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1102 Since Mojarra 2.3-m06 you must be able to use

<ui:repeat begin="1" end="10">
    <div>content</div>
</ui:repeat>

Since it needs a collection, you can make a collection (containing as much elements as the number of time you want to output the divs) in the backing bean:

public class MyBean {
  private List list = new ArrayList<Integer();

  { ... populate the list with numbers, for example ... }

  public List getList() {
     return list;
  }
 ...
}

and then:

<ui:repeat value="#{myBean.list}" var="item">
  <div>content</div>
</ui:repeat>

..which would output as many divs as the size of the list property.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!