6. 注释
可以用注释加入描述性文本,他们并不在模板引擎中输出。注释可以有助于你的记忆或者想其他人解释你的VTL语句正在做什么。
## This is a single line comment. |
单行注释以## 开始,并在本行结束。如果需要加入多行注释,并不需要加入很多的单行注释。多行注释,以#* 开始并以*#结束可以处理这种情况。
This is text that is outside the multi-line comment. Online visitors can see it.
#* Thus begins a multi-line comment. Online visitors won't see this text because the Velocity Templating Engine will ignore it. *#
Here is text outside the multi-line comment; it is visible. |
下面事一些例子说明单行注释和多行注释如何工作。
This text is visible. ## This text is not. This text is visible. This text is visible. #* This text, as part of a multi-line comment, is not visible. This text is not visible; it is also part of the multi-line comment. This text still not visible. *# This text is outside the comment, so it is visible. ## This text is not visible. |
还有第三种注释, VTL 注释块,可以用来存储诸如文档作者、版本信息等。
#** This is a VTL comment block and may be used to store such information as the document author and versioning information: @author @version 5 *# |
7. 引用
VTL中有三种类型的引用:变量,属性和方法。作为使用VTL的设计者,你和你的工程师必须在饮用的特定命名上取得一致,以便在你的模板中正确的使用他们。
有关引用的所有参数都处理为字符串对象。Everything coming to and from a reference is treated as a String object. 假如有一个对象表示$foo (比如说是整型对象),Velocity 将调用其toString() 方法来将此对象转换为一个字符串。
7.1. 变量Variables
变量的简略标记是有一个前导"$"字符后跟一个 VTL 标识符(Identifier.)组成。一个VTL 标识符必须以一个字母开始(a .. z或 A .. Z)。剩下的字符将由以下类型的字符组成:
字母 (a .. z, A .. Z)
数字 (0 .. 9)
连字符("-")
下划线 ("_")
下面是一些有效的变量引用:
$foo $mudSlinger $mud-slinger $mud_slinger $mudSlinger1 |
当VTL 引用一个变量时,比如$foo,变量可以从模板的set 指令取得值,也可以从
Java 代码中取得。例如,如果Java 变量 $foo 在模板被请求的时候具有值bar ,则bar 将替换页面中的所有$foo 的实例。或者,如果包含下面的语句:
#set( $foo = "bar" ) |
紧跟指令后的所有$foo 的实例的输出将会一样值。
7.2. 属性
VTL引用的第二种元素是属性,而属性具有独特的格式。属性的简略标记识前导符$ 后跟一个VTL 标识符,在后跟一个点号(".")最后又是一个VTL 标识符。这是一些有效的示例:
$customer.Address $purchase.Total |
请看第一个例子, $customer.Address.。他有两种意思。 它可以意味着,查询由customer 标是的哈希表并按关键字Address返回值。但是 $customer.Address 也可能引用一个方法(下述,$customer.Address 可能是$customer.getAddress().的缩写。当一个页面被请求时,Velocity 将决定这两种可能到底是哪一个,然后返回相应的值。