Velocity模板(VM)语言介绍(转载)

注意这里的Velocity的数字是作为Integer来比较的――其他类型的对象将使得条件为false,但是与java不同它使用“==”来比较两个值,而且velocity要求等号两边的值类型相同。
关系、逻辑运算符
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

include
#include script element允许模板设计者引入本地文件。被引入文件的内容将不会通过模板引擎被render。为了安全的原因,被引入的本地文件只能在TEMPLATE_ROOT目录下。
  #inclued ( “one.txt” )
如果您需要引入多个文件,可以用逗号分隔就行:
  #include ( “one.gif”, “two.txt”, “three.htm” )
在括号内可以是文件名,但是更多的时候是使用变量的:
  #inclue ( “greetings.txt”, $seasonalstock )

parse
#parse script element允许模板设计者一个包含VTL的本地文件。Velocity将解析其中的VTL并render模板。
  #parse( “me.vm” )
就像#include,#parse接受一个变量而不是一个模板。任何由#parse指向的模板都必须包含在TEMPLATE_ROOT目录下。与#include不同的是,#parse只能指定单个对象。
你可以通过修改velocity.properties文件的parse_direcive.maxdepth的值来控制一个template可以包含的最多#parse的个数――默认值是10。#parse是可以递归调用的,例如:如果dofoo.vm包含如下行:
  Count down.
  #set ( $count = 8 )
  #parse ( “parsefoo.vm” )
  All done with dofoo.vm!
那么在parsefoo.vm模板中,你可以包含如下VTL:
  $count
  #set ( $count = $count – 1 )
  #if ( $count > 0 )
    #parse( “parsefoo.vm” )
  #else
    All done with parsefoo.vm!
  #end
的显示结果为:
  Count down.
  8
  7
  6
  5
  4
  3
  2
  1
  0
  All done with parsefoo.vm!
All done with dofoo.vm!

Stop
#stop script element允许模板设计者停止执行模板引擎并返回。把它应用于debug是很有帮助的。
  #stop

Velocimacros
#macro script element允许模板设计者定义一段可重用的VTL template。例如:
  #macro ( d )
  <tr><td></td></tr>
  #end
在上面的例子中Velocimacro被定义为d,然后你就可以在任何VTL directive中以如下方式调用它:
  #d()
当你的template被调用时,Velocity将用<tr><td></td></tr>替换为#d()。
每个Velocimacro可以拥有任意数量的参数――甚至0个参数,虽然定义时可以随意设置参数数量,但是调用这个Velocimacro时必须指定正确的参数。下面是一个拥有两个参数的Velocimacro,一个参数是color另一个参数是array:
  #macro ( tablerows $color $somelist )
  #foreach ( $something in $somelist )
    <tr><td bgcolor=$color>$something</td</tr>
  #end
  #end
调用#tablerows Velocimacro:
  #set ( $greatlakes = [ “Superior”, “Michigan”, “Huron”, “Erie”, “Ontario” ] )
  #set ( $color = “blue” )
  <table>
    #tablerows( $color $greatlakes )
  </table>
经过以上的调用将产生如下的显示结果:
  <table>
    <tr><td bgcolor=” blue”> Superior </td></tr>
    <tr><td bgcolor=” blue”> Michigan </td></tr>
    <tr><td bgcolor=” blue”> Huron </td></tr>
    <tr><td bgcolor=” blue”> Erie </td></tr>
    <tr><td bgcolor=” blue”> Ontario </td></tr>
  </table>
Velocimacros可以在Velocity模板内实现行内定义(inline),也就意味着同一个web site内的其他Velocity模板不可以获得Velocimacros的定义。定义一个可以被所有模板共享的Velocimacro显然是有很多好处的:它减少了在一大堆模板中重复定义的数量、节省了工作时间、减少了出错的几率、保证了单点修改。
上面定义的#tablerows( $color $list )Velocimacro被定义在一个Velocimacros模板库(在velocity.properties中定义)里,所以这个macro可以在任何规范的模板中被调用。它可以被多次应用并且可以应用于不同的目的。例如下面的调用:
  #set ( $parts = [ “volva”, “stipe”, “annulus”, “gills”, “pileus” ] )
  #set ( $cellbgcol = “#CC00FF” )
  <table>
    #tablerows( $cellbgcol $parts )
  </table>
上面VTL将产生如下的输出:
  <table>
    <tr><td bgcolor=”#CC00FF”> volva </td</tr>
    <tr><td bgcolor=”#CC00FF”> stipe </td</tr>
    <tr><td bgcolor=”#CC00FF”> annulus </td</tr>
    <tr><td bgcolor=”#CC00FF”> gills </td</tr>
    <tr><td bgcolor=”#CC00FF”> pileus </td</tr>
  </table>
  Velocimacro arguments
  Velocimacro可以使用以下任何元素作为参数:
l  Reference:任何以$开头的reference
l  String literal:
l  Number literal:
l  IntegerRange:[1….3]或者[$foo….$bar]
l  对象数组:[“a”,”b”,”c”]
l  boolean值:true、false
当将一个reference作为参数传递给Velocimacro时,请注意reference作为参数时是以名字的形式传递的。这就意味着参数的值在每次Velocimacro内执行时才会被产生。这个特性使得你可以将一个方法调用作为参数传递给Velocimacro,而每次 Velocimacro执行时都是通过这个方法调用产生不同的值来执行的。例如:
  #macro ( callme $a )
    $a $a $a
  #end
  #callme( $foo.bar() )
执行的结果是:reference $foo的bar()方法被执行了三次。
如果你不需要这样的特性可以通过以下方法:
  #set ( $myval = $foo.bar() )
  #callme ( $myval )

Velocimacro properties
Velocity.properties文件中的某几行能够使Velocimacros的实现更加灵活。注意更多的内容可以看Developer Guide。
Velocity.properties文件中的velocimacro.libraary:一个以逗号分隔的模板库列表。默认情况下,velocity查找唯一的一个库:VM_global_library.vm。你可以通过配置这个属性来指定自己的模板库。
Velocity.properties文件中的velocimacro.permissions.allow.inline属性:有两个可选的值true或者false,通过它可以确定 Velocimacros是否可以被定义在regular template内。默认值是ture――允许设计者在他们自己的模板中定义Velocimacros。
Velocity.properties文件中的
velocimacro.permissions.allow.inline.replace.global属性有两个可选值true和 false,这个属性允许使用者确定inline的Velocimacro定义是否可以替代全局Velocimacro定义(比如在 velocimacro.library属性中指定的文件内定义的Velocimacro)。默认情况下,此值为false。这样就阻止本地Velocimacro定义覆盖全局定义。
Velocity.properties文件中的
velocimacro.permissions.allow.inline.local.scale属性也是有true和false两个可选值,默认是false。它的作用是用于确定你inline定义的Velocimacros是否仅仅在被定义的template内可见。换句话说,如果这个属性设置为true,一个inline定义的Velocimacros只能在定义它的template内使用。你可以使用此设置实现一个奇妙的VM敲门:a template can define a private implementation of the second VM that will be called by the first VM when invoked by that template. All other templates are unaffected。
Velocity.properties文件中的velocimacro.context.localscope属性有true和false两个可选值,默认值为false。当设置为true时,任何在Velocimacro内通过#set()对context的修改被认为是针对此velocimacro的本地设置,而不会永久的影响内容。
Velocity.properties文件中的velocimacro.library.autoreload属性控制Velocimacro库的自动加载。默认是false。当设置为ture时,对于一个Velocimacro的调用将自动检查原始库是否发生了变化,如果变化将重新加载它。这个属性使得你可以不用重新启动servlet容器而达到重新加载的效果,就像你使用regular模板一样。这个属性可以使用的前提就是resource loader缓存是off状态(file.resource.loader.cache = false)。注意这个属性实际上是针对开发而非产品的。
Velocimacro Trivia
Velocimacro必须被定义在他们被使用之前。也就是说,你的#macro()声明应该出现在使用Velocimacros之前。
特别要注意的是,如果你试图#parse()一个包含#macro()的模板。因为#parse()发生在运行期,但是解析器在parsetiem决定一个看似VM元素的元素是否是一个VM元素,这样#parse()-ing一组VM声明将不按照预期的样子工作。为了得到预期的结果,只需要你简单的使用velocimacro.library使得Velocity在启动时加载你的VMs。
Escaping VTL directives
VTL directives can be escaped with “\”号,使用方式跟VTL的reference使用逃逸符的格式差不多。
  ## #include( “a.txt” ) renders as <ontents of a.txt>(注释行)
  #include( “a.txt” )

  ## \#include( “a.txt” ) renders as \#include( “a.txt” )
  \#include( “a.txt” )

  ## \\#include ( “a.txt” ) renders as \<contents of a.txt>
  \\#include( “a.txt” )
在对在一个directive内包含多个script元素的VTL directives使用逃逸符时要特别小心(比如在一个if-else-end statement内)。下面是VTL的if-statement的典型应用:
  #if ( $jazz )
    Vyacheslav Ganelin
  #end
如果$jazz是ture,输出将是:
  Vyacheslav Ganelin
如果$jazz是false,将没有输出。使用逃逸符将改变输出。考虑一下下面的情况:
  \#if ( $jazz )
    Vyacheslav Ganelin
  \#end
现在无论$jazz是true还是false,输出结果都是:
  #if ( $jazz )
    Vyacheslav Ganelin
  #end
事实上,由于你使用了逃逸符,$jazz根本就没有被解析为boolean型值。在逃逸符前使用逃逸符是合法的,例如:
  \\#if ( $jazz )
    Vyacheslav Ganelin
  \\#end
以上程序的显示结果为:
  \ Vyacheslav Ganelin
  但是如果$jazz为false,那么将没有输出。(书上说会没有输出,但是我觉得应该还有有“\”字符被输出。)
VTL:Formatting issues
尽管在此用户手册中VTL通常都开始一个新行,如下所示:
  #set ( $imperial = [ “Munetaka”, “Koreyasu”, “Hisakira”, “Morikune” ] )
  #foreach ( $shogun in $imperial )
    $shogun
  #end
但是像下面这种写法也是可以的:
  Send me #set($foo = [“$10 and”,”a cake”])#foreach($a in $foo)$a #end please.
上面的代码可以被改写为:
  Send me
  #set ( $foo = [“$10 and “,”a cake”] )
  #foreach ( $a in $foo )
    $a
  #end
  please.
或者
  Send me
  #set($foo = [“$10 and “,”a cake”])
        #foreach ($a in $foo )$a
      #end please.
这两种的输出结构将一样。
其他特性和杂项
  math   在模板中可以使用Velocity内建的算术函数,如:加、减、乘、除
    #set ( $foo = $bar + 3 )
    #set ( $foo = $bar - 4 )
    #set ( $foo = $bar * 6 )
    #set ( $foo = $bar / 2 )
  当执行除法时将返回一个Integer类型的结果。而余数你可以使用%来得到:
    #set ( $foo = $bar % 5 )
在Velocity内使用数学计算公式时,只能使用像-n,-2,-1,0,1,2,n这样的整数,而不能使用其它类型数据。当一个非整型的对象被使用时它将被logged并且将以null作为输出结果。
Range Operator
Range operator可以被用于与#set和#foreach statement联合使用。对于处理一个整型数组它是很有用的,Range operator具有以下构造形式:
  [n..m]
m和n都必须是整型,而m是否大于n则无关紧要。例子:
  First example:
  #foreach ( $foo in [1..5] )
    $foo
  #end

  Second example:
  #foreach ( $bar in [2..-2] )
    $bar
  #end

  Third example:
  #set ( $arr = [0..1] )
  #foreach ( $i in $arr )
    $i
  #end

  Fourth example:
  [1..3]
上面四个例子的输出结果为:
  First example:
  1 2 3 4 5

  Second example:
  2 1 0 -1 -2

  Third example:
  0 1

  Fourth example:
  [1..3]
注意:range operator只在#set和#foreach中有效。
Advanced Issue:Escaping and!
当一个reference被“!”分隔时,并且在它之前有逃逸符时,reference将以特殊的方式处理。注意这种方式与标准的逃逸方式时不同的。对照如下:
#set ( $foo = “bar” )
特殊形式  标准格式
Render前  Render后  Render前  Render后
$\!foo  $!foo  \$foo  \$foo
$\!{foo}  $!{foo}  \$!foo  \$!foo
$\\!foo  $\!foo  \$!{foo}  \$!{foo}
$\\\!foo  $\\!foo  \\$!{foo}  \bar
Velocimacro杂记
  Can I user a directive or another VM as an argument to a VM?
  例如:#center ( #bold( “hello” ) )
  不可以。一个directive的参数使用另外一个directive是不合法的。
  但是,还是有些事情你可以作的。最简单的方式就是使用双引号:
    #set ( $stuff = “#bold( ‘hello’ )” )
    #center ( $stuff )
  上面的格式也可以缩写为一行:
    #center ( “#bold( ‘hello’ ) )
请注意在下面的例子中参数被evaluated在Velocimacro内部,而不是在calling level。例子:
  #macro ( inner $foo )
    inner : $foo
  #end

  #macro ( outer $foo )
    #set ( $bar = “outerlala” )
    outer : $foo
  #end
 
  #set ( $bar = ‘calltimelala’ )
  #outer( “#inner($bar)” )
输出结果为:
  outer : inner : outerlala
记住Veloctiy的特性:参数的传递是By Name的。例如:
  #macro ( foo $color )
    <tr bgcolor = $color ><td>Hi</td></tr>
    <tr bgcolor = $color ><td>There</td></tr>
  #end

  #foo ( $bar.rowColor() )
以上代码将导致rowColor()方法两次调用,而不是一次。为了避免这种现象的出现,我们可以按照下面的方式执行:
  #set ( $color = $bar.rowColor() )
  #foo ( $color )
can I register velocimacros via #parse()?
目前,Velocimacros必须在第一次被模板调用前被定义。这就意味着你的#macro()声明应该出现在使用Velocimacros之前。
如果你试图#parse()一个包含#macro() directive的模板,这一点是需要牢记的。因为#parse()发生在运行期,但是解析器在parsetiem决定一个看似VM元素的元素是否是一个VM元素,这样#parse()-ing一组VM声明将不按照预期的样子工作。为了得到预期的结果,只需要你简单的使用velocimacro.library使得Velocity在启动时加载你的VMs。
What is velocimacro autoreloading?
velocimacro.library.autoreload是专门为开发而非产品使用的一个属性。此属性的默认值是false。
String concatenation
开发人员最常问的问题是我如何作字符拼接?在java中是使用“+”号来完成的。
在VTL里要想实现同样的功能你只需要将需要联合的reference放到一起就行了。例如:
#set ( $size = “Big” )
#set ( $name = “Ben” )
The clock is $size$name.
输出结果将是:The clock is BigBen.。更有趣的情况是:
  #set ( $size = “Big” )
  #set ( $name = “Ben” )
  #set ( $clokc = “$size$name” )
  The clock is $clock.
上例也会得到同样的结果。最后一个例子,当你希望混合固定字段到你的reference时,你需要使用标准格式:
  #set ( $size = “Big” )
  #set ( $name = “Ben” )
  #set ( $clock = “${size}Tall$name” )
  The clock is $clock.
输出结果是:The clock is BigTallBen.。使用这种格式主要是为了使得$size不被解释为$sizeTall。

http://hi.baidu.com/xinwang0592/blog/modify/772ed52b677f5b185343c1a0

原文地址:https://www.cnblogs.com/zqn518/p/2733969.html