关系、逻辑运算符

Velocity中使用等号操作符判断两个变量的关系。这里有个简单例子关于等于号的使用:

#set ($foo = "deoxyribonucleic acid")

#set ($bar = "ribonucleic acid")

 

#if ($foo == $bar)

  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逻辑运算符。想得到更多信息,请看VTL Reference Guide。下面的例子是说明AND、OR和NOT逻辑运算符的用法:

## logical AND

 

#if( $foo && $bar )

   <strong> This AND that</strong>

#end

只有当$foo 和 $bar 都为true,#if 才会得到true值。如果$foo=false ,表达式的值为 false,$bar 就不会求值。如果 $foo的值为 true ,Velocity模板引擎会检查 $bar的值,如果$bar=true,整个表达式的值为true,输出为“This AND that”。如果$bar=false,整个表达式的值为false,没有输出。

逻辑OR 的工作方式一样,除了只要有一个值为true ,整个表达式的值就为true。考虑一下下面的例子。

## logical OR

 

#if( $foo || $bar )

    <strong>This OR That</strong>

#end

如果$foo=true,Velocity模板引擎就没有必要查找 $bar,无论 $bar 是true 还是 false ,表达式的值为 true ,输出为“This OR That”。如果$foo=flase,$bar的值就一定要检查,在这个例子中,如果 $bar 同样是false,表达式的值为 false ,没有输出。从另外一个角度看,如果$bar 的值为true ,整个表达式的值为 true ,输出为 “This OR That”。

关于逻辑NOT ,只有一个疑问:

##logical NOT

 

#if( !$foo )

  <strong>NOT that</strong>

#end

如果 $foo=true, !$foo 的值为 false,没有输出。如果$foo=false,!$foo的值为true,输出为“NOT that”。注意不要跟 quiet reference $!foo 混为一谈,那是完全不一样的。

posted @ 2010-01-12 14:23  蔡剑锋  阅读(1006)  评论(0编辑  收藏  举报