欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Velocity运算符,循环

程序员文章站 2022-07-12 21:31:36
...

关系、逻辑运算符

Velocity 中使用等号操作符判断两个变量的关系。例如:

#set ( $foo = “deoxyribonucleic acid” )

#set ( $bar = “ribonucleic acid” )

#if ( $foo == $foo )

In this case it’s clear they aren’t equivalent.So…

#else

They are not equivalent and this will be the output.

#end

Velocity 有AND、OR 和NOT 逻辑运算符。下面是一些例子:

## logical AND

 

#if( $foo && $bar )

<strong> This AND that </strong>

#end

## logical OR

#if ( $foo || $bar )

<strong>This OR That </strong>

#end

##logical NOT

#if ( !$foo )

<strong> NOT that </strong>

#end

 

 

循环

Foreach循环

例子:

<ul>

#foreach ( $product in $allProducts )

<li> $product </li>

#end

</ul>

每次循环$allProducts 中的一个值都会赋给$product 变量。

$allProducts 可以是一个Vector、Hashtable 或者Array。分配给$product 的值是

一个java 对象,并且可以通过变量被引用。例如:如果$product 是一个java 的

Product 类,并且这个产品的名字可以通过调用他的getName()方法得到。

现在我们假设$allProducts 是一个Hashtable,如果你希望得到它的key 应该像下面

这样:

<ul>

#foreach ( $key in $allProducts.keySet() )

<li>Key: $key -> Value: $allProducts.get($key) </li>

#end

</ul>

Velocity 还特别提供了得到循环次数的方法,以便你可以像下面这样作:

<table>

#foreach ( $customer in $customerList )

<tr><td>$velocityCount</td><td>$customer.Name</td></tr>

#end

</table>

$velocityCount 变量的名字是Velocity 默认的名字, 你也可以通过修改

velocity.properties 文件来改变它。默认情况下,计数从“1”开始,但是你可以在

velocity.properties 设置它是从“1”还是从“0”开始。下面就是文件中的配置:

# Default name of loop counter

# variable reference

directive.foreach.counter.name = velocityCount

 

# Default starting value of the loop

# counter variable reference

directive.foreach.counter.initial.value = 1