当在velocity中需要显示一个列表信息,我们会用foreach循环输出,
要求:
假如现在需要在页面中输出单数的内容背景为红,双数的内容为黑,构造方式如下:
package org.apache.velocity.test.issues;
import java.util.ArrayList;
import java.util.List;
import org.apache.velocity.test.BaseTestCase;
/**
* 测试foreach
* @author madding.lip at 2011.07.28
*/
public class MaddingTestForeach extends BaseTestCase {
public MaddingTestForeach(String name) {
super(name);
}
public void test() {
List<String> list = new ArrayList<String>();
for(int i = 1; i <= 100; i++) {
list.add(String.valueOf(i));
}
context.put("features", list);
String template =
"#foreach ($feature in $features)" +
"#if($velocityCount%2 == 1)" +
"<font color=\"red\">$feature</font>" +
"#elseif($velocityCount%2 == 0)" +
"<font color=\"black\">$feature</font>" +
"#end" +
"#if($velocityHasNext)" +
"|" +
"#end" +
"#end";
System.out.println(evaluate(template));
}
}
BaseTestCase是Velocity源代码中的测试类
说明:
1.#foreach是velocity指令,
2.velcotiyCount上, velocity foreach定义的一个变量,该变量主要用来记录当前的循环次数
3.velocityHasNext, velocity foreach定义的一个变量 ,表明该循环当前是否到尾部了
velocity.properties:
# ----------------------------------------------------------------------------
# F O R E A C H P R O P E R T I E S
# ----------------------------------------------------------------------------
# These properties control how the counter is accessed in the #foreach
# directive. By default the reference $velocityCount and $velocityHasNext
# will be available in the body of the #foreach directive.
# The default starting value for $velocityCount is 1.
# ----------------------------------------------------------------------------
directive.foreach.counter.name = velocityCount
directive.foreach.counter.initial.value = 1
directive.foreach.maxloops = -1
directive.foreach.iterator.name = velocityHasNext