## 12.1. #set
`#set` 指令用來為引用設置相應的值。值可以被值派給變量引用或者是屬性引用,而且賦值要在括號里括起來。
```
#set( $primate = "monkey" )
#set( $customer.Behavior = $primate )
```
賦值的左邊必須是一個變量應用或者是屬性引用。右邊可以是下面的類型之一:
+ 變量引用
+ 字面字符串
+ 屬性引用
+ 方法引用
+ 字面數字
+ 數組列表
這些例子演示了上述的每種類型:
```
#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
```
注意:最后一個例子中,在方括號[..] 中定義的項目可以被ArrayList 類定義的方法訪問。比如,你可以使用$monkey.Say.get(0)訪問上述的第一個元素。
右邊也可以是一個簡單的算術表達式:
```
#set( $value = $foo + 1 )
#set( $value = $bar - 1 )
#set( $value = $foo * $bar )
#set( $value = $foo / $bar )
```
如果右邊是一個屬性或方法引用,取值是NULL,他將不會賦值給左邊。通過這種機制將一個存在的引用從上下文中刪除是不可能的。這對Velocity的新手可能會混淆。例如:
```
#set( $result = $query.criteria("name") )
The result of the first query is $result
#set( $result = $query.criteria("address") )
The result of the second query is $result
```
如果, $query.criteria("name") 放回字符串"bill",而$query.criteria("address") 返回 null,上述VTL 將解釋為:
```
The result of the first query is bill
The result of the second query is bill
```
這往往會給那些想構建#foreach循環來試圖通過屬性和方法引用來設置一個引用的新手帶來困惑,下面馬上通過#if指令測試一下。例如:
```
#set( $criteria = ["name", "address"] )
#foreach( $criterion in $criteria )
#set( $result = $query.criteria($criterion) )
#if( $result )
Query was successful
#end
#end
```
在上面的例子中,依靠$result 的去值來決定查詢是否成功恐怕不是英明的做法。當$result 被#set設置后(添加到上下文中),他就不能再被設值為null (從上下文中刪除)。
我們對此的解決方法是預設$result 為 false。然后如果 $query.criteria() 調用失敗,你就可以檢查之。
```
#set( $criteria = ["name", "address"] )
#foreach( $criterion in $criteria )
#set( $result = false )
#set( $result = $query.criteria($criterion) )
#if( $result )
Query was successful
#end
#end
```
不象其他Velocity 指令, #set 指令沒有#end 語句。
- 1. 關于
- 2. 什么是Velocity?
- 3. Velocity 可以做什么?
- 3.1. Mud Store 示例
- 4. Velocity模板語言(VTL): 介紹
- 5. Hello Velocity World!
- 6. 注釋
- 7. 引用
- 7.1. 變量Variables
- 7.2. 屬性
- 7.3. 方法
- 8. 形式引用符Formal Reference Notation
- 9. 安靜引用符Quiet Reference Notation
- 11. Case Substitution
- 12. 指令
- 12.1. #set
- 12.2. 字面字符串
- 12.3. 條件
- 12.3.1 If / ElseIf / Else
- 12.3.2 關系和邏輯操作符
- 12.4. 循環
- 12.4.1. Foreach 循環
- 12.5. 包含
- 12.6. 解析
- 12.7. 停止
- 12.10. 宏
- 12.10.1. Velocimacro 參數
- 12.10.2. Velocimacro 屬性
- 12.10.3. Velocimacro Trivia
- 13. Getting literal
- 13.1. 貨幣字符
- 13.2. 轉義 有效的 VTL 指令
- 13.3. 轉義 無效的 VTL 指令
- 14. VTL 格式化問題
- 15. 其它特征和雜項
- 15.1. 數學特征
- 15.2. 范圍操作符
- 15.3. 進階:轉義和!
- 15.4. Velocimacro 雜記
- 15.5. 字符串聯