当前位置: 代码迷 >> Web前端 >> Velocity 的根本语法
  详细解决方案

Velocity 的根本语法

热度:894   发布时间:2012-09-04 14:19:30.0
Velocity 的基本语法

????????????????????????????????????????????????????????? Velocity 的基本语法
最近项目用的jpa整合ssh,view用的velocity,稍微总结学习下:
1.“#”用来标识velocity的脚本语句
#set
#if、#else、#end
#foreach、#end
#iinclude
#parse
#macro
2.“$”用来标识一个对象;
如:$i、$msg
3.“{}”用来明确标识velocity变量
4.“!”用来强制把不存在的变量显示为空白
页面包含$msg,如果msg对象有值,则显示如果不存在,则显示“$msg”字符,这是我们不愿意看到的,那么把不存在的变量变为null或者空白,则可以写成“$!msg”。
语法摘要:
1.声明:#set($var=XXX)
左边可以是:
variable reference
String literal
property reference
number literal #set($i=1)
ArrayList #set($arr = ["a","b"])

2.注释
单行##XXX
多行#*XX
??XXX
?*#
?
3.变量variable
以"$"开头,?第一个字符必须为字母。
变量可以包含的字符有以下内容:
alphabetic(a..z,A..Z)字母
numeric(0..9) 数字
hyphen("-") 连字号
underscore("_")

4.Properties
$Identifier
$user.name

5.Methods
object user.getName() = $user.getName()

6.Formal Reference Notation
用{}把变量名跟字符串分开


#set ($user="csy"}
${user}name
返回csyname

$username
$!username
$与$!的区别
当找不到username的时候,$username返回字符串"$username",而$!username返回空字符串""

7、双引号 与 引号
#set ($var="helo")
test"$var" 返回testhello
test'$var' 返回test'$var'
可以通过设置 stringliterals.interpolate=false改变默认处理方式

8、条件语句
#if( $foo )
<strong>Velocity!</strong>
#end
#if($foo)
#elseif()
#else
#end
当$foo为null或为Boolean对象的false值执行.

9、逻辑运算符:== && || !

10、循环语句#foreach($var in $arrays ) // 集合包含下面三种Vector, a Hashtable or an Array
#end
#foreach( $product in $allProducts )
<li>$product</li>
#end

#foreach( $key in $allProducts.keySet() )
<li>Key: $key -> Value: $allProducts.get($key)</li>
#end

#foreach( $customer in $customerList )
<tr><td>$velocityCount</td><td>$customer.Name</td></tr>
#end

11、velocityCount变量在配置文件中定义
# Default name of the loop counter
# variable reference.
directive.foreach.counter.name = velocityCount
# Default starting value of the loop
# counter variable reference.
directive.foreach.counter.initial.value = 1

12、包含文件
#include( "one.gif","two.txt","three.htm" )

13、Parse导入脚本
#parse("me.vm" )

14、#stop 停止执行并返回

15、定义宏Velocimacros ,相当于函数 支持包含功能
#macro( d )
<tr><td></td></tr>
#end
调用
#d()

16、带参数的宏
#macro( tablerows $color $somelist )
#foreach( $something in $somelist )
<tr><td bgcolor=$color>$something</td></tr>
#end
#end

17、Range Operator
#foreach( $foo in [1..5] )