Velocity用户指南(中文版)(3)(完)

本文介绍了Velocity模板引擎中Velocimacros的使用方法。包括其可在VTL模板中内联定义或在全局模板库中定义以实现共享,还说明了在velocity.properties文件中定义的相关属性,强调其需在首次使用前定义,以及引用作为参数的传递形式等内容。

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

指令(Directives)

引用允许模板设计者为Web站点生成动态内容,而指令使巧妙处理Java代码的脚本元素容易使用。

1#set

格式:#set( LHS = RHS )

l         LHS可以是变量引用或属性引用

l         RHS可以是引用、字符串、数字、ArrayListMap

下面的例子展示了上面的每种RHS类型:

#set( $monkey = $bill ) ## variable reference
#set( $monkey.Friend = "monica" ) ## string literal
#set( $monkey.Blame = $whitehouse.Leak ) ## property reference
#set( $monkey.Plan = $spindoctor.weave($web) ) ## method reference
#set( $monkey.Number = 123 ) ##number literal
#set( $monkey.Say = ["Not", $my, "fault"] ) ## ArrayList
#set( $monkey.Map = {"banana" : "good", "roast beef" : "bad"}) ## Map

对于ArrayListMap,可以使用对应的Java方法访问其中的元素值:

$monkey.Say.get(0)
$monkey.Map.get("bannana")
$monkey.Map.banana ## same as above

l         RHS可以是简单的算术表达式

#set( $value = $foo + 1 ) ## Addition
#set( $value = $bar - 1 ) ## Subtraction
#set( $value = $foo * $bar ) ## Multiplication
#set( $value = $foo / $bar ) ## Division
#set( $value = $foo % $bar ) ## Remainder

算术表达式只支持整型。/的结果为整数;如果非整型数值,返回null

l         如果RHS的结果为null,是不会赋值给LHS

看下面的例子:

#set( $criteria = ["name", "address"] )
#foreach( $criterion in $criteria )
    #set( $result = $query.criteria($criterion) )
    #if( $result )
        Query was successful
    #end
#end

上面使用$result检查是否执行成功是有问题的。如果第一次执行成功,$result不为null,则后面的执行不管是否成功,检查条件总是成立。改进的方法是在每次执行前初始化为false

#set( $criteria = ["name", "address"] )
#foreach( $criterion in $criteria )
#set( $result = false )
    #set( $result = $query.criteria($criterion) )
    #if( $result )
        Query was successful
    #end
#end

l         String文字可以使用双引号或单引号括起。两者的主要区别是双引号中的引用会替换成相应的值,而单引号中的引用原样输出

#set( $directoryRoot = "www" )
#set( $templateName = "index.vm" )
#set( $template = "$directoryRoot/$templateName" )
$template

输出结果是:www/index.vm

如果使用单引号:

#set( $template = '$directoryRoot/$templateName )

输出结果是:$directoryRoot/$templateName

l         使用双引号可以实现字符串的串联,如下面的例子:

      #set( $size = "Big" )
      #set( $name = "Ben" )
      #set($clock = "${size}Tall$name" )
      The clock is $clock.

2#if / #elseif / #else

#if指令在条件成立时,显示#if#end之间的内容,否则显示#else#end之间的内容。下面是一个例子:

#if( $foo )
   Velocity!
#end

条件成立有两种情况:

l         如果$fooboolean,则$foo要为true

l         否则,$foo不为null

#if指令中可以使用的关系和逻辑符号包括:

l         <<===>=>

l         &&(and)||(or)!(not)

3)循环:foreach

下面是一个例子:

    #foreach( $product in $allProducts )
        
    • $product
    #end

      $allProducts的内容可以是VectorHashtableArrayList,每次取出一个值赋值给$product;返回的值是一个Java对象,可以用来引用具体的方法。下面的例子假设$allProductsHashtable对象:

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

          Velocity提供了访问循环计数变量的简单方法:

          #foreach( $customer in $customerList )
              
          $velocityCount$customer.Name
          #end

          $velocityCountVelocity表示循环计数的内部变量,缺省开始值为1。该设置在velocity.properties文件中定义:

          # 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

          可以在#foreach指令中使用范围操作符[n..m],其中nm必须是整型:

          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

          输出结果是:

          First example:
          1 2 3 4 5
          Second example:
          2 1 0 -1 -2
          Third example:
          0 1

          4#include

          #include指令导入本地文件到#include指令定义的地方。导入的文件内容不会被模板引擎解析。出于安全考虑,导入的文件应该放在TEMPLATE_ROOT目录下。一次可以导入多个文件,文件名之间用逗号分隔;并且通常使用变量引用来替代文件名。下面是一个例子:

          #include( "greetings.txt", $seasonalstock )

          5#parse

          #parse指令允许导入一个包含VTL的本地文件,并由模板引擎进行解析。#parse指令导入的文件必须放在TEMPLATE_ROOT目录下,并且一次只能导入一个文件。允许在Velocity模板中嵌套执行#parse指令。最大深度由velocity.properties文件中的parse_directive.maxdepth定义。下面是一个例子:

          Count down.
          #set( $count = 8 )
          #parse( "parsefoo.vm" )
          All done with dofoo.vm!

          包含的parsefoo.vm文件如下:

          $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!

          6#stop

          #stop指令停止模板引擎的执行并返回。这在Debug时很有用。

          7#macro

          #macro指令允许定义一段重复使用的VTL模板(称Velocimacros)。

          l         Velocimacros可以有0或多个参数。下面是一个例子:

          #macro( tablerows $color $somelist )
          #foreach( $something in $somelist )
              
          $something
          #end
          #end

          这个叫tablerowsVelocimacro2个参数:一个color和一个array。下面的代码包含对

          tablerows的调用:

          #set( $greatlakes = ["Superior","Michigan","Huron","Erie","Ontario"] )
          #set( $color = "blue" )
              #tablerows( $color $greatlakes )
           

          输出结果为:

              
          Superior
              
          Michigan
              
          Huron
              
          Erie
              
          Ontario

          l         Velocimacros可以在VTL模板中定义为inline,这样对其它的VTL模板是无效的;要使Velocimacros在所有VTL模板中共享,可以将Velocimacros定义在Velocimacros模板库(全局)中。

          l         Velocimacros属性在velocity.properties文件中定义,提供实现Velocimacros的灵活性:

          velocimacro.library = VM_global_library.vm
          velocimacro.permissions.allow.inline = true
          velocimacro.permissions.allow.inline.to.replace.global = false
          velocimacro.permissions.allow.inline.local.scope = false
          velocimacro.context.localscope = false
          velocimacro.library.autoreload = false

          velocimacro.library:定义逗号分隔的Velocimacros全局模板库,缺省是VM_global_library.vm,可以增加自定义的模板库;

          velocimacro.permissions.allow.inline:指定是否允许在VTL模板中定义Velocimacros,缺省是true(允许);

          velocimacro.permissions.allow.inline.to.replace.global:指定是否允许inline定义的Velocimacros替换同名的全局Velocimacros,缺省是false(不允许);

          velocimacro.permissions.allow.inline.local.scope:指定inline定义是否是定义的模板中可见,缺省是false

          velocimacro.context.localscope:指定context内容是否是本地范围的,缺省是false;如果设为true,则使用#set指令对context做的修改只在本地范围有效,不会永久性的影响context

          velocimacro.library.autoreload指定是否自动装载Velocimacros模板库,缺省是false;如果设为true,则在调用Velocimacros模板库中的Velocimacro时,会检查模板库是否更新,并在需要时重新装载;使用前提是file.resource.loader.cache = false;该属性应该在开发时使用,而不是产品阶段;

          l         Velocimacros必须在第一次使用之前进行定义。因此#parse指令包含inline定义的Velocimacros的模板会有问题,简单的解决方法就是将Velocimacros定义到模板库中,以便Velocity启动时装载。

          l         引用作为Velocimacros的参数时,是使用by name形式的,这意味在Velocimacros内部每次使用时才会获得其值

          l         Velocimacros的不能作为参数传递给另一个Velocimacros,如:

          #center( #bold("hello") ) ##invalid

          你可以采用下面的形式达到同样的目的:

          #center( "#bold( 'hello' )"  ) ##right

          下面是一个嵌套调用的例子:

          #macro( inner $foo )
            inner : $foo
          #end
          #macro( outer $foo )
             #set($bar = "outerlala")
             outer : $foo
          #end
          #set($bar = 'calltimelala')
          #outer( "#inner($bar)" )

          输出的结果是:Outer : inner : outerlala

          因为参数以by name形式传递,在#outer内部先设置$bar的值,再调用#inner

          评论
          添加红包

          请填写红包祝福语或标题

          红包个数最小为10个

          红包金额最低5元

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

          抵扣说明:

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

          余额充值