velcoity使用说明:foreach指令

本文介绍如何使用Velocity模板引擎中的foreach指令来遍历列表,并通过条件判断改变不同项的显示样式,例如根据列表项的奇偶性分别设置背景颜色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当在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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值