posts - 54,  comments - 1,  trackbacks - 0

Velocity 参考资料

John Zhu

2005-4-7

 

原文:http://jakarta.apache.org/velocity/user-guide.html

VTL Reference: http://jakarta.apache.org/velocity/vtl-reference-guide.html

Developer's Guide: http://jakarta.apache.org/velocity/developer-guide.html

Comments

单行注释

<!--[if !vml]--><!--[endif]-->## This is a single line comment.

多行注释

#*

 Thus begins a multi-line comment. Online visitors won't

 see this text because the Velocity Templating Engine will

 ignore it.

*#

注释块: 作者,版本,日期

#**

This is a VTL comment block and

may be used to store such information

as the document author and versioning

information:

@author

@version 5

*#

References

变量:

consists of a leading "$" character followed by a VTL Identifier. A VTL Identifier must start with an alphabetic character (a .. z or A .. Z). The rest of the characters are limited to the following types of characters:

  • alphabetic (a .. z, A .. Z)

  • numeric (0 .. 9)

  • hyphen ("-")

  • underscore ("_")

$foo

$mudSlinger

$mud-slinger

$mud_slinger

$mudSlinger1

<!--[if !vml]--><!--[endif]-->

属性:

consists of a leading $ character followed a VTL Identifier, followed by a dot character (".") and another VTL Identifier.

 

$customer.Address

$purchase.Total

<!--[if !vml]--><!--[endif]-->

方法:

consist of a leading "$" character followed a VTL Identifier, followed by a VTL Method Body. A VTL Method Body consists of a VTL Identifier followed by an left parenthesis character ("("), followed by an optional parameter list, followed by right parenthesis character (")").

$customer.getAddress()

$purchase.getTotal()

$page.setTitle( "My Home Page" )

$person.setAttributes( ["Strange", "Weird", "Excited"] )

<!--[if !vml]--><!--[endif]-->

Formal Reference Notation:

 

${mudSlinger}

${customer.Address}

${purchase.getTotal()}

<!--[if !vml]--><!--[endif]-->

In almost all cases you will use the shorthand notation for references, but in some cases the formal notation is required for correct processing.For example:

Jack is a $vicemaniac.

Jack is a ${vice}maniac.

<!--[if !vml]--><!--[endif]-->

Quiet Reference Notation:

When Velocity encounters an undefined reference, its normal behavior is to output the image of the reference.

<input type="text" name="email" value="$email"/>

如果$email没有初始化,则将原样列出:

<!--[if !vml]--><!--[endif]-->


 
<!--[if !vml]--><!--[endif]--> <input type="text" name="email" value="$!email"/>

使用静态引用,即使没有初始化,也是显示一个空字符串:

<!--[if !vml]--><!--[endif]--> <!--[if !vml]--><!--[endif]-->

 

特殊字符

货币符号:

a VTL identifier always begins with an upper- or lowercase letter, so $2.50 would not be mistaken for a reference.

 

转义符:

backslash ( \ ) character.

 

1. $email is defined

#set( $email = "foo" )

$email

\$email

\\$email

\\\$email

output:

foo

$email

\foo

\$email

 

2. $email is not defined:


 
<!--[if !vml]--><!--[endif]-->
 
<!--[if !vml]--><!--[endif]-->$email

\$email

\\$email

\\\$email

<!--[if !vml]--><!--[endif]--> output:

$email

\$email

\\$email

\\\$email

<!--[if !vml]--><!--[endif]-->

3.变量赋值:

#set( $foo = "gibbous" )

$moon = $foo

<!--[if !vml]--><!--[endif]--> output:

$moon = gibbous

 

4. Escaping VTL Directives

## #include( "a.txt" ) renders as <contents 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" )

 

等价用法

$foo

 

$foo.getBar()

## is the same as

$foo.Bar

 

$data.setUser("jon")

## is the same as

#set( $data.User = "jon" )

 

$data.getRequest().getServerName()

## is the same as

$data.Request.ServerName

## is the same as

${data.Request.ServerName}

 

Directives

Directives always begin with a #. Like references, the name of the directive may be bracketed by a { and a } symbol.

 

#set

The #set directive is used for setting the value of a reference. A value can be assigned to either a variable reference or a property reference.

#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

<!--[if !vml]--><!--[endif]-->NOTE:

<!--[if !supportLists]-->1.      <!--[endif]-->ArrayList example the elements defined with the [..] operator are accessible using the methods defined in the ArrayList class.Such as: $monkey.Say.get(0).

<!--[if !supportLists]-->2.      <!--[endif]-->Map example, the elements defined within the { } operator are accessible using the methods defined in the Map class.Such as: $monkey.Map.get("bannana")

<!--[if !supportLists]-->3.      <!--[endif]-->If the RHS(right hand side) is a property or method reference that evaluates to null, it will not be assigned to the LHS(left hand side).

<!--[if !supportLists]-->4.      <!--[endif]-->#set directive does not have an #end statement.

<!--[if !supportLists]-->5.      <!--[endif]-->字符串: enclosed in double quote characters will be parsed and rendered, enclosed in single quote characters, it will not be parsed:

#set( $directoryRoot = "www" )

#set( $templateName = "index.vm" )

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

$template

output:

www/index.vm


 
<!--[if !vml]--><!--[endif]-->

#set( $foo = "bar" )

$foo

#set( $blargh = '$foo' )

$blargh

output:

bar

    $foo

 

Conditionals

If / ElseIf / Else

 

#if( $foo )

   <strong>Velocity!</strong>

#end

$foo is evaluated to be true under one of two circumstances:

<!--[if !supportLists]-->(i)                  <!--[endif]-->$foo is a boolean (true/false) which has a true value.

<!--[if !supportLists]-->(ii)                <!--[endif]-->the value is not null.

 

#if( $foo < 10 )

    <strong>Go North</strong>

#elseif( $foo == 10 )

    <strong>Go East</strong>

#elseif( $bar == 6 )

    <strong>Go South</strong>

#else

    <strong>Go West</strong>

#end

 

Relational and Logical Operators

 

#set ($foo = "deoxyribonucleic acid")

#set ($bar = "ribonucleic acid")

 

## equivalent operator ==

#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

 

## 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

 

Loops

Foreach Loop

 

<ul>

#foreach( $product in $allProducts )

    <li>$product</li>

#end

</ul>

the $allProducts variable is a Vector, a Hashtable or an Array

 

<table>

#foreach( $customer in $customerList )

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

#end

</table>

The default name for the loop counter variable reference, which is specified in the velocity.properties file, is $velocityCount. By default the counter starts at 1, but this can be set to either 0 or 1 in the velocity.properties file.

 

Include

The #include script element allows the template designer to import a local file, which is then inserted into the location where the #include directive is defined. The contents of the file are not rendered through the template engine. For security reasons, the file to be included may only be under TEMPLATE_ROOT.

#include( "one.txt" )

#include( "one.gif","two.txt","three.htm" )


 
<!--[if !vml]--><!--[endif]-->#include( "greetings.txt", $seasonalstock )

<!--[if !vml]--><!--[endif]-->

Parse

The #parse script element allows the template designer to import a local file that contains VTL. Velocity will parse the VTL and render the template specified

 

#parse( "me.vm" )

<!--[if !vml]--><!--[endif]-->

可以迭代Parse:

dofoo.vm:

Count down.

#set( $count = 8 )

#parse( "parsefoo.vm" )

All done with dofoo.vm!

<!--[if !vml]--><!--[endif]-->

parsefoo.vm

$count

#set( $count = $count - 1 )

#if( $count > 0 )

    #parse( "parsefoo.vm" )

#else

    All done with parsefoo.vm!

#end

 

Stop

The #stop script element allows the template designer to stop the execution of the template engine and return. This is useful for debugging purposes.

<!--[if !vml]--><!--[endif]-->

#stop

 

Velocimacros

The #macro script element allows template designers to define a repeated segment of a VTL template.

#macro( d )

<tr><td></td></tr>

#end

 

#d()

 

A Velocimacro could take any number of arguments

#macro( tablerows $color $somelist )

#foreach( $something in $somelist )

    <tr><td bgcolor=$color>$something</td></tr>

#end

#end

 

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

#set( $color = "blue" )

<table>

    #tablerows( $color $greatlakes )

</table>

output:

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

 

Velocimacro Arguments

Velocimacros can take as arguments any of the following VTL elements :

  • Reference : anything that starts with '$'

  • String literal : something like "$foo" or 'hello'

  • Number literal : 1, 2 etc

  • IntegerRange : [ 1..2] or [$foo .. $bar]

  • ObjectArray : [ "a", "b", "c"]

  • boolean value true

  • boolean value false

Velocimacro Properties ()

Several lines in the velocity.properties file allow for flexible implementation of Velocimacros.

Note: Velocimacros must be defined before they are first used in a template.

This is important to remember if you try to #parse() a template containing inline #macro() directives. Because the #parse() happens at runtime, and the parser decides if a VM-looking element in the template is a VM at parsetime, #parse()-ing a set of VM declarations won't work as expected.

 

Velocimacros –FAQ:

Q:Can I use a directive or another VM as an argument to a VM?

   Example : #center( #bold("hello") )

A: No. A directive isn't a valid argument to a directive, and for most practical purposes, a VM is a directive.can do like follow:

#set($stuff = "#bold('hello')" )

#center( $stuff )

the argument to the VM is passed in in its entirety and evaluated within the VM it was passed into.like:

#macro( inner $foo )

     inner : $foo

#end

   

#macro( outer $foo )

      #set($bar = "outerlala")

      outer : $foo

#end

 

#set($bar = 'calltimelala')

#outer( "#inner($bar)" )

output:

Outer : inner : outerlala

<!--[if !vml]--><!--[endif]-->

Q: Can I register Velocimacros via #parse() ?

A:No, Velocimacros must be defined before they are first used in a template.

To get around this, simply use the velocimacro.library facility to have Velocity load your VMs at startup.

 

Q: What is Velocimacro Autoreloading?

A: here is a property, meant to be used in development, not production :

<type>.resource.loader.path = templates

    <type>.resource.loader.cache = false

    velocimacro.library.autoreload = true

(where <type> is the name of the resource loader that you are using, such as 'file').

Then the Velocity engine will automatically reload changes to your Velocimacro library files when you make them

Other Features and Miscellany

Math

#set( $foo = $bar + 3 )

#set( $foo = $bar - 4 )

#set( $foo = $bar * 6 )

#set( $foo = $bar / 2 )

<!--[if !vml]--><!--[endif]--> <!--[if !vml]--><!--[endif]-->#set( $foo = $bar % 5 )

 

Range Operator

[n..m]

 

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]

output:

First example:

1 2 3 4 5

 

Second example:

2 1 0 -1 -2

 

Third example:

0 1

 

Fourth example:

[1..3]

 

Advanced Issues: Escaping and !

 

the special case where \ precedes ! follows it:

#set( $foo = "bar" )

$\!foo

$\!{foo}

$\\!foo

$\\\!foo

output:

$!foo

$!{foo}

$\!foo

$\\!foo

<!--[if !vml]--><!--[endif]-->

regular escaping, where \ precedes $:

\$foo

\$!foo

\$!{foo}

\\$!{foo}

<!--[if !vml]--><!--[endif]-->output:

$foo

$!foo

$!{foo}

\bar

 

字符串连接:

just have to 'put them together'.like:

## Example 1

#set( $size = "Big" )

#set( $name = "Ben" )

The clock is $size$name.

Output:

The clock is BigBen

 

## Example 2

#set( $size = "Big" )

#set( $name = "Ben" )

#set($clock = "$size$name" )

The clock is $clock.

Output:

The clock is BigBen

 

## Example 3

#set( $size = "Big" )

#set( $name = "Ben" )

#set($clock = "${size}Tall$name" )

The clock is $clock.

Output:

The clock is BigTallBen

posted on 2006-01-02 23:25 ZhuJun 阅读(691) 评论(0)  编辑  收藏 所属分类: 开发手记开源项目

只有注册用户登录后才能发表评论。


网站导航:
 

蜀中人氏,躬耕于珠海

<2006年1月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
2930311234

常用链接

留言簿(2)

随笔分类(71)

随笔档案(54)

博客

文档

站点

论坛

搜索

  •  

积分与排名

  • 积分 - 50299
  • 排名 - 981

最新评论

阅读排行榜