Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

How to repeat output of some content in JSF using only standard tags (ui:, h: etc) ? In other words - how to do equivalent to PHP code below in JSF ? I immediately wanted to take advantage of ui:repeat, but it needs collection - I have only number.

for ($i = 0; $i < 10; $i++) {
    echo "<div>content</div>";
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JSF 2.3+

If you're already on JSF 2.3+ then you can use begin/end attributes of <ui:repeat>.

xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
...
<ui:repeat begin="1" end="10">
    <div>content</div>
</ui:repeat>

JSF 2.2-

If you're not on JSF 2.3 yet, then 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...