├── Snippets ├── cparse.tmSnippet ├── set.tmSnippet ├── if.tmSnippet ├── ${variable_within_string}.tmSnippet ├── foreach.tmSnippet └── ifelse.tmSnippet ├── Preferences └── Indent.tmPreferences ├── README.md ├── info.plist ├── Syntaxes ├── Velocity (HTML).tmLanguage └── Velocity.tmLanguage └── Test ├── sample.vm └── Velocity Syntax.vm /Snippets/cparse.tmSnippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | content 6 | #cparse("${1:path_to_include}") 7 | name 8 | cparse 9 | scope 10 | source.velocity, text.html.velocity 11 | tabTrigger 12 | cparse 13 | uuid 14 | 5B997664-BB8C-4070-8FA1-865014D8CE41 15 | 16 | 17 | -------------------------------------------------------------------------------- /Snippets/set.tmSnippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | content 6 | #set(\$${1:variable} = ${2:"${3:value}"}) 7 | name 8 | set 9 | scope 10 | source.velocity, text.html.velocity 11 | tabTrigger 12 | set 13 | uuid 14 | F76873FB-3054-449C-A809-9B96A4B98C7C 15 | 16 | 17 | -------------------------------------------------------------------------------- /Snippets/if.tmSnippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | content 6 | #if(${1:condition}) 7 | #${2:thing_to_do} 8 | #end 9 | name 10 | if 11 | scope 12 | source.velocity, text.html.velocity 13 | tabTrigger 14 | if 15 | uuid 16 | E48E3984-9BCD-4028-90BB-DE04F9D445CC 17 | 18 | 19 | -------------------------------------------------------------------------------- /Snippets/${variable_within_string}.tmSnippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | content 6 | \${${1:$TM_SELECTED_TEXT}} 7 | keyEquivalent 8 | $ 9 | name 10 | ${variable_within_string} 11 | scope 12 | string.quoted.double.velocity 13 | uuid 14 | B836C046-8A0D-40A6-99D7-CB1B40A3C187 15 | 16 | 17 | -------------------------------------------------------------------------------- /Preferences/Indent.tmPreferences: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | name 6 | Indent 7 | scope 8 | source.velocity 9 | settings 10 | 11 | decreaseIndentPattern 12 | ^\s*\#end 13 | indentNextLinePattern 14 | ^\s*\#(if|foreach) 15 | 16 | uuid 17 | F6CD26BE-72BF-46EC-8962-598C1812407A 18 | 19 | 20 | -------------------------------------------------------------------------------- /Snippets/foreach.tmSnippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | content 6 | #foreach(\$${1:temp_variable} in \$${2:array}) 7 | #${3:thing_to_do} 8 | #end 9 | name 10 | foreach 11 | scope 12 | source.velocity, text.html.velocity 13 | tabTrigger 14 | foreach 15 | uuid 16 | EDEE782B-9D6E-4F94-B24F-E4ADA87FD6F5 17 | 18 | 19 | -------------------------------------------------------------------------------- /Snippets/ifelse.tmSnippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | content 6 | #if(${1:condition}) 7 | #${2:thing_to_do} 8 | #else 9 | #${3:otherwise} 10 | #end 11 | name 12 | ifelse 13 | scope 14 | source.velocity, text.html.velocity 15 | tabTrigger 16 | ifelse 17 | uuid 18 | 05B427B3-4EAA-482A-9FF2-2A3D89F08A04 19 | 20 | 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **How to install from GitHub** 2 | 3 | 1. Click the "Download Source" button. 4 | 2. Unzip the download 5 | 3. Rename the folder to `whatever.tmbundle` 6 | 4. Double-click 7 | 5. TextMate handles the rest! 8 | 9 | --- 10 | 11 | TextMate Bundle for Java Velocity Syntax 12 | ==== 13 | 14 | It's not an exhaustive implementation, but it's at least good enough to bother using ;) 15 | 16 | If you notice any issues please be sure to report them! 17 | 18 | I don't actually use Velocity anymore personally so I'm not implementing any new features. 19 | I do try to fix any major bugs that people find from time to time. 20 | 21 | If you're interested in taking over maintainance, do let me know. 22 | 23 | Thanks! 24 | -------------------------------------------------------------------------------- /info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | contactEmailRot13 6 | boyvivbhf+irybpvgl@fhogyrTenqvrag.pbz 7 | contactName 8 | Thomas Aylott 9 | description 10 | Support for the <a href="http://velocity.apache.org/engine/devel/user-guide.html">Velocity</a> templating language. 11 | name 12 | Java Velocity 13 | ordering 14 | 15 | B836C046-8A0D-40A6-99D7-CB1B40A3C187 16 | EDEE782B-9D6E-4F94-B24F-E4ADA87FD6F5 17 | F76873FB-3054-449C-A809-9B96A4B98C7C 18 | 5B997664-BB8C-4070-8FA1-865014D8CE41 19 | E48E3984-9BCD-4028-90BB-DE04F9D445CC 20 | 05B427B3-4EAA-482A-9FF2-2A3D89F08A04 21 | 460426C7-D079-49DB-8E50-8E0B938644CA 22 | ECA114B6-F103-4D5B-BD0A-9CCD9F797018 23 | F6CD26BE-72BF-46EC-8962-598C1812407A 24 | 25 | uuid 26 | 44339853-BBEB-44BF-9E69-B70E8E040B4C 27 | 28 | 29 | -------------------------------------------------------------------------------- /Syntaxes/Velocity (HTML).tmLanguage: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | fileTypes 6 | 7 | fhtml 8 | 9 | foldingStartMarker 10 | (?x) 11 | ( 12 | \#(?: 13 | (?:macro|if|foreach)\b \s* \( 14 | |\{ (?:macro|if|foreach)\b \s* \( 15 | ).*(?!\#\{?end).*$ 16 | ) 17 | | # Copied from HTML 18 | (<(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|li|form|dl)\b.*?> 19 | |<!--(?!.*--\s*>) 20 | |^<!--\ \#tminclude\ (?>.*?-->)$ 21 | |<\?(?:php)?.*\b(if|for(each)?|while)\b.+: 22 | |\{\{?(if|foreach|capture|literal|foreach|php|section|strip) 23 | |\{\s*($|\?>\s*$|//|/\*(.*\*/\s*$|(?!.*?\*/))) 24 | ) 25 | foldingStopMarker 26 | (?x) 27 | (\#end\b|\#\{end) 28 | 29 | 30 | | # Copied from HTML 31 | (</(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|li|form|dl)> 32 | |^(?!.*?<!--).*?--\s*> 33 | |^<!--\ end\ tminclude\ -->$ 34 | |<\?(?:php)?.*\bend(if|for(each)?|while)\b 35 | |\{\{?/(if|foreach|capture|literal|foreach|php|section|strip) 36 | |^[^{]*\} 37 | ) 38 | keyEquivalent 39 | ^@V 40 | name 41 | Velocity (HTML) 42 | patterns 43 | 44 | 45 | include 46 | text.html.basic 47 | 48 | 49 | include 50 | text.velocity 51 | 52 | 53 | include 54 | #leading-space 55 | 56 | 57 | repository 58 | 59 | leading-space 60 | 61 | patterns 62 | 63 | 64 | begin 65 | ^(?=(\t| )) 66 | end 67 | (?=[^\t\s]|\n) 68 | name 69 | meta.leading-tabs 70 | patterns 71 | 72 | 73 | captures 74 | 75 | 1 76 | 77 | name 78 | meta.odd-tab.group1.spaces 79 | 80 | 10 81 | 82 | name 83 | meta.even-tab.group10.spaces 84 | 85 | 11 86 | 87 | name 88 | meta.odd-tab.group11.spaces 89 | 90 | 2 91 | 92 | name 93 | meta.even-tab.group2.spaces 94 | 95 | 3 96 | 97 | name 98 | meta.odd-tab.group3.spaces 99 | 100 | 4 101 | 102 | name 103 | meta.even-tab.group4.spaces 104 | 105 | 5 106 | 107 | name 108 | meta.odd-tab.group5.spaces 109 | 110 | 6 111 | 112 | name 113 | meta.even-tab.group6.spaces 114 | 115 | 7 116 | 117 | name 118 | meta.odd-tab.group7.spaces 119 | 120 | 8 121 | 122 | name 123 | meta.even-tab.group8.spaces 124 | 125 | 9 126 | 127 | name 128 | meta.odd-tab.group9.spaces 129 | 130 | 131 | match 132 | ( )( )?( )?( )?( )?( )?( )?( )?( )?( )?( )? 133 | 134 | 135 | captures 136 | 137 | 1 138 | 139 | name 140 | meta.odd-tab.group1.tab 141 | 142 | 10 143 | 144 | name 145 | meta.even-tab.group10.tab 146 | 147 | 11 148 | 149 | name 150 | meta.odd-tab.group11.tab 151 | 152 | 2 153 | 154 | name 155 | meta.even-tab.group2.tab 156 | 157 | 3 158 | 159 | name 160 | meta.odd-tab.group3.tab 161 | 162 | 4 163 | 164 | name 165 | meta.even-tab.group4.tab 166 | 167 | 5 168 | 169 | name 170 | meta.odd-tab.group5.tab 171 | 172 | 6 173 | 174 | name 175 | meta.even-tab.group6.tab 176 | 177 | 7 178 | 179 | name 180 | meta.odd-tab.group7.tab 181 | 182 | 8 183 | 184 | name 185 | meta.even-tab.group8.tab 186 | 187 | 9 188 | 189 | name 190 | meta.odd-tab.group9.tab 191 | 192 | 193 | match 194 | (\t)(\t)?(\t)?(\t)?(\t)?(\t)?(\t)?(\t)?(\t)?(\t)?(\t)? 195 | 196 | 197 | 198 | 199 | 200 | 201 | scopeName 202 | text.html.velocity 203 | uuid 204 | ECA114B6-F103-4D5B-BD0A-9CCD9F797018 205 | 206 | 207 | -------------------------------------------------------------------------------- /Test/sample.vm: -------------------------------------------------------------------------------- 1 | ${thing.getPrimaryCategory().property}## 2 | 3 |

4 | #set( $demo = $text.demo ) 5 | $demo.thisPage.insert("#doclink( 'ResourceTool' true )"). This tool 6 | is similar to the LinkTool in that most methods 7 | return a new object that has mostly the same methods as the original, allowing you 8 | to build up parameters elegantly and simply, rather than try to remember how to use 9 | methods with many parameters that must be in a specific order. So, you can access a 10 | resource with the key 'hello.whoever' in the 'otherStuff' bundle with one message 11 | argument like this: 12 |

 13 |   ${esc.d}text.hello.whoever.bundle('otherStuff').insert('World')
 14 | 
15 | instead of like this: 16 |
 17 |   ${esc.d}text.get('hello.whoever','otherStuff', $null, 'World')
 18 | 
19 | While the former is somewhat longer, it is much more understandable and flexible. 20 |

21 | 22 | #demoTableStart() 23 | 24 | #set( $desc = 'Returns the resource with the specified name, if it exists.' ) 25 | #demo1( 'text' 'get' 9 $desc ) 26 | 27 | #set( $desc = 'Returns a list of the available keys.' ) 28 | #demo( 'text' 'hello.keys' $desc ) 29 | 30 | #set( $desc = 'Returns a new $text that will search only the specified bundle (if it exists) for the resource "foo".' ) 31 | #demo1( 'text.foo' 'bundle' 9 $desc ) 32 | 33 | #set( $quote = '' ) 34 | #set( $desc = 'Returns a new $text that will try to find the resource "foo" for the specified Locale.' ) 35 | #demo1( 'text.foo' 'locale' 9 $desc ) 36 | 37 | #set( $quote = '"' ) 38 | #set( $desc = 'Returns the resource "hello.whoever" with the specified value inserted.' ) 39 | #demo1( 'text.hello.whoever' 'insert' 9 $desc ) 40 | 41 | #set( $desc = 'Returns the resource "baz" with the specified values inserted.' ) 42 | #demo2( 'text.baz' 'insert' 9 $desc ) 43 | 44 | #demoCustom( 'text' ) 45 | 46 | 47 |
48 |

$demo.mainExampleHeader

49 |
50 | 60 |
61 | 62 | #if( $params.layout ) 63 | 64 | #end 65 |
66 | 67 | #if( $params.demo ) 68 | $demo.mainResultsIntro: 69 |
 70 |   $render.eval($params.demo)
 71 | 
72 | #end 73 |
74 | 75 | 76 | #* 77 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor 78 | 79 | doesn't seem to like a single apostrophe in comments 80 | 81 | *# 82 | 83 | 84 |

85 | #set( $demo = $text.demo ) 86 | $demo.thisPage.insert("#doclink( 'MathTool' true )"). 87 |

88 | 89 | #demoTableStart() 90 | 91 | #set( $desc = 'Returns the sum of the numbers or null if they are invalid.' ) 92 | #demo2( 'math' 'add' 3 $desc) 93 | 94 | #set( $desc = 'Returns the difference of the numbers or null if they are invalid.' ) 95 | #demo2( 'math' 'sub' 3 $desc) 96 | 97 | #set( $desc = 'Returns the product of the numbers or null if they are invalid.' ) 98 | #demo2( 'math' 'mul' 3 $desc) 99 | 100 | #set( $desc = 'Returns the quotient of the numbers or null if they are invalid.' ) 101 | #demo2( 'math' 'div' 3 $desc) 102 | 103 | #set( $desc = 'Returns the first number raised to the power of the second or null if they are invalid.' ) 104 | #demo2( 'math' 'pow' 3 $desc) 105 | 106 | #set( $desc = 'Returns the result of performing integer division on the operands or null if they are invalid.' ) 107 | #demo2( 'math' 'idiv' 3 $desc) 108 | 109 | #set( $desc = 'Returns the result of performing integer modulus on the operands or null if they are invalid.' ) 110 | #demo2( 'math' 'mod' 3 $desc) 111 | 112 | #set( $desc = 'Returns the largest of the numbers or null if they are invalid.' ) 113 | #demo2( 'math' 'max' 3 $desc) 114 | 115 | #set( $desc = 'Returns the smallest of the numbers or null if they are invalid.' ) 116 | #demo2( 'math' 'min' 3 $desc) 117 | 118 | #set( $desc = 'Returns the absolute value of the number or null if it is invalid.' ) 119 | #demo2( 'math' 'abs' 3 $desc) 120 | 121 | #set( $desc = 'Returns the smallest integer that is not less than the given number or null if it is invalid.' ) 122 | #demo1( 'math' 'ceil' 3 $desc) 123 | 124 | #set( $desc = 'Returns the integer portion of the given number or null if it is invalid.' ) 125 | #demo1( 'math' 'floor' 3 $desc) 126 | 127 | #set( $desc = 'Returns the given number rounded to the nearest whole Integer or null if it is invalid.' ) 128 | #demo1( 'math' 'found' 3 $desc) 129 | 130 | #set( $desc = "Rounds a number to the specified number of decimal places. This is particulary useful for simple display formatting. If you want to round an number to the nearest integer, it is better to use ${esc.d}math.round(), as that will return an Integer rather than a Double." ) 131 | #demo2( 'math' 'roundTo' 2 $desc ) 132 | 133 | #set( $desc = 'Returns a pseudo-random Double greater than or equal to 0.0 and less than 1.0' ) 134 | #demo( 'math' 'random' $desc ) 135 | 136 | #set( $desc = 'This returns a random Number within the specified range. The returned value will be greater than or equal to the first number and less than the second number. If both arguments are whole numbers then the returned number will also be, otherwise a Double will be returned.' ) 137 | #demo2( 'math' 'random' 3 $desc ) 138 | 139 | #set( $desc = 'Converts an object with a numeric value into an Integer. Valid formats are Number or a string representation of a number.' ) 140 | #demo1( 'math' 'toInteger' 3 $desc ) 141 | 142 | #set( $desc = 'Converts an object with a numeric value into a Double. Valid formats are Number or a string representation of a number.' ) 143 | #demo1( 'math' 'toDouble' 3 $desc ) 144 | 145 | #set( $desc = 'Converts an object with a numeric value into a Number. Valid formats are Number or a string representation of a number.' ) 146 | #demo1( 'math' 'toNumber' 3 $desc ) 147 | 148 | #demoCustom( 'math' ) 149 | 150 | -------------------------------------------------------------------------------- /Syntaxes/Velocity.tmLanguage: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | fileTypes 6 | 7 | vm 8 | 9 | foldingStartMarker 10 | (?x) 11 | \#(?: 12 | (?:macro|if|foreach)\b \s* \( 13 | |\{ (?:macro|if|foreach)\b \s* \( 14 | ).*(?!\#\{?end).*$ 15 | foldingStopMarker 16 | \#end\b|\#\{end 17 | keyEquivalent 18 | ^@V 19 | name 20 | Velocity 21 | patterns 22 | 23 | 24 | captures 25 | 26 | 0 27 | 28 | name 29 | constant.character.escape.backslash.velocity 30 | 31 | 32 | match 33 | \\[\!\#\$\\] 34 | name 35 | source.velocity.embedded 36 | 37 | 38 | include 39 | #directives 40 | 41 | 42 | include 43 | #function 44 | 45 | 46 | include 47 | #variable 48 | 49 | 50 | beginCaptures 51 | 52 | 0 53 | 54 | name 55 | comment.line.double-number-sign 56 | 57 | 1 58 | 59 | name 60 | punctuation.definition.comment.velocity 61 | 62 | 63 | match 64 | (\#\#).*$\n? 65 | name 66 | source.velocity.embedded 67 | 68 | 69 | begin 70 | (?=#\*) 71 | end 72 | (?<=\*#|\*#\n) 73 | name 74 | source.velocity.embedded 75 | patterns 76 | 77 | 78 | begin 79 | \#\*\* 80 | captures 81 | 82 | 0 83 | 84 | name 85 | punctuation.definition.comment.velocity 86 | 87 | 88 | end 89 | \*\#\n? 90 | name 91 | comment.block.documentation 92 | 93 | 94 | begin 95 | \#\* 96 | captures 97 | 98 | 0 99 | 100 | name 101 | punctuation.definition.comment.velocity 102 | 103 | 104 | end 105 | \*\#\n? 106 | name 107 | comment.block 108 | 109 | 110 | 111 | 112 | repository 113 | 114 | array 115 | 116 | patterns 117 | 118 | 119 | captures 120 | 121 | 1 122 | 123 | name 124 | punctuation.definition.constant.range.begin.java 125 | 126 | 2 127 | 128 | name 129 | constant.numeric.integer.java 130 | 131 | 3 132 | 133 | name 134 | punctuation.separator.continuation.range.java 135 | 136 | 4 137 | 138 | name 139 | constant.numeric.integer.java 140 | 141 | 5 142 | 143 | name 144 | punctuation.definition.constant.range.end.java 145 | 146 | 147 | match 148 | (\[)(-?\d+)(\.\.)(-?\d+)(\]) 149 | name 150 | meta.definition.range.java 151 | 152 | 153 | begin 154 | \[ 155 | beginCaptures 156 | 157 | 0 158 | 159 | name 160 | punctuation.definition.array.begin.velocity 161 | 162 | 163 | end 164 | \] 165 | endCaptures 166 | 167 | 0 168 | 169 | name 170 | punctuation.definition.array.end.velocity 171 | 172 | 173 | name 174 | meta.structure.array.velocity 175 | patterns 176 | 177 | 178 | include 179 | #nest-brackets 180 | 181 | 182 | include 183 | #function 184 | 185 | 186 | include 187 | #variable 188 | 189 | 190 | include 191 | #array 192 | 193 | 194 | include 195 | #string 196 | 197 | 198 | include 199 | #constant 200 | 201 | 202 | include 203 | #operators 204 | 205 | 206 | match 207 | , 208 | name 209 | punctuation.separator.array.velocity 210 | 211 | 212 | 213 | 214 | 215 | constant 216 | 217 | patterns 218 | 219 | 220 | match 221 | \b(true|false|null)\b 222 | name 223 | constant.language.java 224 | 225 | 226 | match 227 | \b((0(x|X)[0-9a-fA-F]*)|(([0-9]+\.?[0-9]*)|(\.[0-9]+))((e|E)(\+|-)?[0-9]+)?)\b 228 | name 229 | constant.numeric.velocity 230 | 231 | 232 | 233 | directives 234 | 235 | patterns 236 | 237 | 238 | captures 239 | 240 | 0 241 | 242 | name 243 | keyword.control.directive.velocity 244 | 245 | 1 246 | 247 | name 248 | punctuation.definition.keyword.velocity 249 | 250 | 2 251 | 252 | name 253 | punctuation.definition.keyword.begin.velocity 254 | 255 | 3 256 | 257 | name 258 | punctuation.definition.keyword.end.velocity 259 | 260 | 261 | match 262 | (?x) 263 | (\#) (?: 264 | \b(?:else|end)\b 265 | |(\{) \b(?:else|end)\b (\}) 266 | ) 267 | name 268 | source.velocity.embedded 269 | 270 | 271 | begin 272 | ((#)\b(?:macro)\b)\s*(\() 273 | beginCaptures 274 | 275 | 1 276 | 277 | name 278 | storage.type.macro.velocity 279 | 280 | 2 281 | 282 | name 283 | punctuation.definition.keyword.velocity 284 | 285 | 3 286 | 287 | name 288 | punctuation.definition.parameters.begin.velocity 289 | 290 | 291 | end 292 | (\)) 293 | endCaptures 294 | 295 | 1 296 | 297 | name 298 | punctuation.definition.parameters.begin.velocity 299 | 300 | 301 | name 302 | source.velocity.embedded 303 | patterns 304 | 305 | 306 | captures 307 | 308 | 1 309 | 310 | name 311 | entity.name.type.module.macro.velocity 312 | 313 | 314 | match 315 | (?<=#macro\()\s*([_a-zA-Z][-a-zA-Z0-9_]*) 316 | 317 | 318 | include 319 | #directives-arguments 320 | 321 | 322 | 323 | 324 | begin 325 | ((#)\b(?:set)\b)\s*(\() 326 | beginCaptures 327 | 328 | 1 329 | 330 | name 331 | storage.type.variable.velocity 332 | 333 | 2 334 | 335 | name 336 | punctuation.definition.keyword.velocity 337 | 338 | 3 339 | 340 | name 341 | punctuation.definition.parameters.begin.velocity 342 | 343 | 344 | end 345 | (\)) 346 | endCaptures 347 | 348 | 1 349 | 350 | name 351 | punctuation.definition.parameters.begin.velocity 352 | 353 | 354 | name 355 | source.velocity.embedded 356 | patterns 357 | 358 | 359 | include 360 | #directives-arguments 361 | 362 | 363 | 364 | 365 | begin 366 | ((#)\b(?:if|elseif|foreach)\b)\s*(\() 367 | beginCaptures 368 | 369 | 1 370 | 371 | name 372 | keyword.control.directive.velocity 373 | 374 | 2 375 | 376 | name 377 | punctuation.definition.keyword.velocity 378 | 379 | 3 380 | 381 | name 382 | punctuation.definition.arguments.begin.velocity 383 | 384 | 385 | end 386 | (\)) 387 | endCaptures 388 | 389 | 1 390 | 391 | name 392 | punctuation.definition.arguments.begin.velocity 393 | 394 | 395 | name 396 | source.velocity.embedded 397 | patterns 398 | 399 | 400 | include 401 | #directives-arguments 402 | 403 | 404 | 405 | 406 | begin 407 | ((#)\b(?:[a-zA-Z][-a-zA-Z0-9_]*)\b)\s*(\() 408 | beginCaptures 409 | 410 | 1 411 | 412 | name 413 | entity.name.function.velocity 414 | 415 | 2 416 | 417 | name 418 | punctuation.definition.function.velocity 419 | 420 | 3 421 | 422 | name 423 | punctuation.definition.arguments.begin.velocity 424 | 425 | 426 | end 427 | (\)) 428 | endCaptures 429 | 430 | 1 431 | 432 | name 433 | punctuation.definition.arguments.begin.velocity 434 | 435 | 436 | name 437 | source.velocity.embedded 438 | patterns 439 | 440 | 441 | include 442 | #directives-arguments 443 | 444 | 445 | 446 | 447 | begin 448 | ((#)\b(?:[a-zA-Z][-a-zA-Z0-9_]*)\b)\s*(\() 449 | beginCaptures 450 | 451 | 1 452 | 453 | name 454 | entity.name.function.velocity 455 | 456 | 2 457 | 458 | name 459 | punctuation.definition.function.velocity 460 | 461 | 3 462 | 463 | name 464 | punctuation.definition.arguments.begin.velocity 465 | 466 | 467 | end 468 | (\)) 469 | endCaptures 470 | 471 | 1 472 | 473 | name 474 | punctuation.definition.arguments.begin.velocity 475 | 476 | 477 | name 478 | source.velocity.embedded 479 | patterns 480 | 481 | 482 | include 483 | #directives-arguments 484 | 485 | 486 | 487 | 488 | 489 | directives-arguments 490 | 491 | patterns 492 | 493 | 494 | include 495 | #nest-parens 496 | 497 | 498 | include 499 | #directives 500 | 501 | 502 | include 503 | #function 504 | 505 | 506 | include 507 | #variable 508 | 509 | 510 | include 511 | #array 512 | 513 | 514 | include 515 | #string 516 | 517 | 518 | include 519 | #constant 520 | 521 | 522 | include 523 | #operators 524 | 525 | 526 | 527 | function 528 | 529 | patterns 530 | 531 | 532 | beginCaptures 533 | 534 | 0 535 | 536 | name 537 | meta.function-call.method.with-arguments.velocity 538 | 539 | 1 540 | 541 | name 542 | variable.other.readwrite.velocity 543 | 544 | 2 545 | 546 | name 547 | punctuation.definition.variable.velocity 548 | 549 | 3 550 | 551 | name 552 | variable.parameter.velocity 553 | 554 | 4 555 | 556 | name 557 | punctuation.separator.parameters.velocity 558 | 559 | 5 560 | 561 | name 562 | entity.name.function.velocity 563 | 564 | 6 565 | 566 | name 567 | punctuation.definition.function.velocity 568 | 569 | 7 570 | 571 | name 572 | punctuation.definition.arguments.begin.velocity 573 | 574 | 575 | match 576 | (?x) 577 | ((\$ \!? ) [a-zA-Z][-a-zA-Z0-9_]* \b) 578 | ( (?:(\.) [a-zA-Z][-a-zA-Z0-9_]* \b)* ) 579 | ( (?:(\.) [a-zA-Z][-a-zA-Z0-9_]* \b)+ ) (\(\s*\)) 580 | 581 | name 582 | source.velocity.embedded 583 | 584 | 585 | begin 586 | (?x) 587 | ((\$ \!? ) [a-zA-Z][-a-zA-Z0-9_]* \b) 588 | ( (?:(\.) [a-zA-Z][-a-zA-Z0-9_]* \b)* ) 589 | ( (?:(\.) [a-zA-Z][-a-zA-Z0-9_]* \b)+ ) (\()\s* 590 | 591 | beginCaptures 592 | 593 | 0 594 | 595 | name 596 | meta.function-call.method.with-arguments.velocity 597 | 598 | 1 599 | 600 | name 601 | variable.other.readwrite.velocity 602 | 603 | 2 604 | 605 | name 606 | punctuation.definition.variable.velocity 607 | 608 | 3 609 | 610 | name 611 | variable.parameter.velocity 612 | 613 | 4 614 | 615 | name 616 | punctuation.separator.parameters.velocity 617 | 618 | 5 619 | 620 | name 621 | entity.name.function.velocity 622 | 623 | 6 624 | 625 | name 626 | punctuation.definition.function.velocity 627 | 628 | 7 629 | 630 | name 631 | punctuation.definition.arguments.begin.velocity 632 | 633 | 634 | end 635 | \s*(\)) 636 | endCaptures 637 | 638 | 1 639 | 640 | name 641 | punctuation.definition.arguments.end.velocity 642 | 643 | 644 | name 645 | source.velocity.embedded 646 | patterns 647 | 648 | 649 | include 650 | #function-arguments 651 | 652 | 653 | 654 | 655 | begin 656 | (?x) 657 | \$ \!? \{ 658 | 659 | captures 660 | 661 | 0 662 | 663 | name 664 | punctuation.section.embedded.begin.velocity 665 | 666 | 667 | end 668 | \} 669 | endCaptures 670 | 671 | 0 672 | 673 | name 674 | punctuation.section.embedded.end.velocity 675 | 676 | 677 | name 678 | source.velocity.embedded 679 | patterns 680 | 681 | 682 | captures 683 | 684 | 0 685 | 686 | name 687 | meta.function-call.method.with-arguments.velocity 688 | 689 | 1 690 | 691 | name 692 | entity.name.function.velocity 693 | 694 | 2 695 | 696 | name 697 | punctuation.definition.arguments.velocity 698 | 699 | 700 | match 701 | (\w+)(\(\)) 702 | name 703 | variable.other.readwrite.velocity 704 | 705 | 706 | begin 707 | (\w+)(\() 708 | captures 709 | 710 | 0 711 | 712 | name 713 | meta.function-call.method.with-arguments.velocity 714 | 715 | 1 716 | 717 | name 718 | entity.name.function.velocity 719 | 720 | 2 721 | 722 | name 723 | punctuation.definition.arguments.begin.velocity 724 | 725 | 726 | end 727 | \) 728 | endCaptures 729 | 730 | 0 731 | 732 | name 733 | punctuation.definition.arguments.end.velocity 734 | 735 | 736 | name 737 | variable.other.readwrite.velocity 738 | patterns 739 | 740 | 741 | include 742 | #function-arguments 743 | 744 | 745 | 746 | 747 | match 748 | \w+ 749 | name 750 | variable.other.readwrite.velocity 751 | 752 | 753 | match 754 | \. 755 | name 756 | punctuation.separator.parameters.velocity 757 | 758 | 759 | 760 | 761 | 762 | function-arguments 763 | 764 | patterns 765 | 766 | 767 | captures 768 | 769 | 1 770 | 771 | name 772 | punctuation.definition.arguments.end.velocity 773 | 774 | 2 775 | 776 | name 777 | meta.function-call.method.with-arguments.velocity 778 | 779 | 3 780 | 781 | name 782 | entity.name.function.velocity 783 | 784 | 4 785 | 786 | name 787 | punctuation.definition.function.velocity 788 | 789 | 5 790 | 791 | name 792 | punctuation.definition.arguments.begin.velocity 793 | 794 | 795 | match 796 | (?x) 797 | \s* (\))( ( (?:(\.) [a-zA-Z][-a-zA-Z0-9_]* \b)+ ) (\()\s* ) 798 | 799 | 800 | 801 | include 802 | #nest-parens 803 | 804 | 805 | include 806 | #directives 807 | 808 | 809 | include 810 | #function 811 | 812 | 813 | include 814 | #variable 815 | 816 | 817 | include 818 | #array 819 | 820 | 821 | include 822 | #string 823 | 824 | 825 | include 826 | #constant 827 | 828 | 829 | include 830 | #operators 831 | 832 | 833 | 834 | keyword 835 | 836 | patterns 837 | 838 | 839 | match 840 | \b(if|while|for|in|foreach|return|ifelse|else|case|macro|end|stop)\b 841 | name 842 | keyword.control.velocity 843 | 844 | 845 | match 846 | \b(set|parse|cparse|config|include|cinclude)\b 847 | name 848 | keyword.velocity 849 | 850 | 851 | 852 | nest-brackets 853 | 854 | patterns 855 | 856 | 857 | begin 858 | \[ 859 | end 860 | \] 861 | patterns 862 | 863 | 864 | include 865 | #nest-parens 866 | 867 | 868 | 869 | 870 | 871 | nest-curly 872 | 873 | patterns 874 | 875 | 876 | begin 877 | \{ 878 | end 879 | \} 880 | patterns 881 | 882 | 883 | include 884 | #nest-parens 885 | 886 | 887 | 888 | 889 | 890 | nest-parens 891 | 892 | patterns 893 | 894 | 895 | begin 896 | \( 897 | end 898 | \) 899 | patterns 900 | 901 | 902 | include 903 | #nest-parens 904 | 905 | 906 | 907 | 908 | 909 | operators 910 | 911 | patterns 912 | 913 | 914 | match 915 | \bin\b 916 | name 917 | keyword.operator.assignment.java 918 | 919 | 920 | match 921 | (==|!=|<=|>=|<>|<|>) 922 | name 923 | keyword.operator.comparison.java 924 | 925 | 926 | match 927 | = 928 | name 929 | keyword.operator.assignment.java 930 | 931 | 932 | match 933 | (\-\-|\+\+) 934 | name 935 | keyword.operator.increment-decrement.java 936 | 937 | 938 | match 939 | (\-|\+|\*|\/|%) 940 | name 941 | keyword.operator.arithmetic.java 942 | 943 | 944 | match 945 | (!|&&|\|\|) 946 | name 947 | keyword.operator.logical.java 948 | 949 | 950 | 951 | string 952 | 953 | patterns 954 | 955 | 956 | begin 957 | " 958 | end 959 | " 960 | name 961 | string.quoted.double.velocity 962 | patterns 963 | 964 | 965 | match 966 | \\. 967 | name 968 | constant.character.escape.velocity 969 | 970 | 971 | include 972 | #directives 973 | 974 | 975 | include 976 | #function 977 | 978 | 979 | include 980 | #variable 981 | 982 | 983 | begin 984 | \$\{ 985 | end 986 | \} 987 | name 988 | source.velocity.embedded.source 989 | 990 | 991 | 992 | 993 | begin 994 | ' 995 | end 996 | ' 997 | name 998 | string.quoted.single.velocity 999 | patterns 1000 | 1001 | 1002 | match 1003 | \\' 1004 | name 1005 | constant.character.escape.velocity 1006 | 1007 | 1008 | 1009 | 1010 | 1011 | variable 1012 | 1013 | patterns 1014 | 1015 | 1016 | captures 1017 | 1018 | 1 1019 | 1020 | name 1021 | variable.other.readwrite.velocity 1022 | 1023 | 10 1024 | 1025 | name 1026 | punctuation.definition.variable.end.velocity 1027 | 1028 | 2 1029 | 1030 | name 1031 | punctuation.definition.variable.velocity 1032 | 1033 | 3 1034 | 1035 | name 1036 | variable.parameter.velocity 1037 | 1038 | 4 1039 | 1040 | name 1041 | punctuation.separator.parameters.velocity 1042 | 1043 | 5 1044 | 1045 | name 1046 | variable.other.readwrite.velocity 1047 | 1048 | 6 1049 | 1050 | name 1051 | punctuation.definition.variable.begin.velocity 1052 | 1053 | 7 1054 | 1055 | name 1056 | variable.parameter.velocity 1057 | 1058 | 8 1059 | 1060 | name 1061 | punctuation.separator.parameters.velocity 1062 | 1063 | 9 1064 | 1065 | name 1066 | variable.other.readwrite.velocity 1067 | 1068 | 1069 | match 1070 | (?x) 1071 | ((\$ \!? ) [a-zA-Z][-a-zA-Z0-9_]*) \b ( (?: (\.) [a-zA-Z][-a-zA-Z0-9_]* \b)+ ) (?!\() 1072 | |((\$ \!? \{) [a-zA-Z][-a-zA-Z0-9_]*) \b ( (?: (\.) [a-zA-Z][-a-zA-Z0-9_]* \b)+ ) ((\})) 1073 | 1074 | name 1075 | source.velocity.embedded 1076 | 1077 | 1078 | captures 1079 | 1080 | 0 1081 | 1082 | name 1083 | variable.other.readwrite.velocity 1084 | 1085 | 1 1086 | 1087 | name 1088 | punctuation.definition.variable.velocity 1089 | 1090 | 2 1091 | 1092 | name 1093 | punctuation.definition.variable.begin.velocity 1094 | 1095 | 3 1096 | 1097 | name 1098 | punctuation.definition.variable.end.velocity 1099 | 1100 | 1101 | match 1102 | (?x) 1103 | (\$ \!? ) [a-zA-Z][-a-zA-Z0-9_]* \b 1104 | |(\$ \!? \{) [a-zA-Z][-a-zA-Z0-9_]* \b (\}) 1105 | 1106 | name 1107 | source.velocity.embedded 1108 | 1109 | 1110 | 1111 | 1112 | scopeName 1113 | text.velocity 1114 | uuid 1115 | 460426C7-D079-49DB-8E50-8E0B938644CA 1116 | 1117 | 1118 | -------------------------------------------------------------------------------- /Test/Velocity Syntax.vm: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | Apache Velocity - Velocity User Guide 7 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 26 | 37 |
38 | 98 |
99 |
100 |
101 | 102 |
103 |

User Guide - Contents

104 |
    105 |
  1. About this Guide
  2. 106 |
  3. What is Velocity?
  4. 107 |
  5. 108 | What can Velocity do for me? 109 |
      110 |
    1. The Mud Store example
    2. 111 |
    112 |
  6. 113 |
  7. Velocity Template Language (VTL): An Introduction
  8. 114 |
  9. Hello Velocity World!
  10. 115 |
  11. Comments
  12. 116 |
  13. 117 | References 118 |
      119 |
    1. Variables
    2. 120 |
    3. Properties
    4. 121 |
    5. Methods
    6. 122 |
    7. Property Lookup Rules
    8. 123 |
    124 |
  14. 125 |
  15. Formal Reference Notation
  16. 126 |
  17. Quiet Reference Notation
  18. 127 |
  19. 128 | Getting literal 129 |
      130 |
    1. Currency
    2. 131 |
    3. Escaping Valid VTL References
    4. 132 |
    133 |
  20. 134 |
  21. Case Substitution
  22. 135 |
  23. 136 | Directives 137 |
      138 |
    1. Set
    2. 139 |
    3. Literals
    4. 140 |
    5. 141 | If-Else Statements 142 |
        143 |
      1. Relational and Logical Operators
      2. 144 |
      145 |
    6. 146 |
    7. Foreach Loops
    8. 147 |
    9. Include
    10. 148 |
    11. Parse
    12. 149 |
    13. Stop
    14. 150 |
    15. Evaluate
    16. 151 |
    17. Velocimacros
    18. 152 |
    153 |
  24. 154 |
  25. Escaping VTL Directives
  26. 155 |
  27. VTL: Formatting Issues
  28. 156 |
  29. 157 | Other Features and Miscellany 158 |
      159 |
    1. Math
    2. 160 |
    3. Range Operator
    4. 161 |
    5. Advanced Issues: Escaping and !
    6. 162 |
    7. Velocimacro Miscellany
    8. 163 |
    9. String Concatenation
    10. 164 |
    165 |
  30. 166 |
  31. Feedback
  32. 167 |
168 |
169 |
170 |

About this Guide

171 |

The Velocity User Guide is intended to help page designers and content providers get acquainted with Velocity and the syntax of its simple yet powerful scripting language, the Velocity Template Language (VTL). Many of the examples in this guide deal with using Velocity to embed dynamic content in web sites, but all VTL examples are equally applicable to other pages and templates.

172 |

Thanks for choosing Velocity!

173 |
174 |
175 |

What is Velocity?

176 |

Velocity is a Java-based template engine. It permits web page designers to reference methods defined in Java code. Web designers can work in parallel with Java programmers to develop web sites according to the Model-View-Controller (MVC) model, meaning that web page designers can focus solely on creating a well-designed site, and programmers can focus solely on writing top-notch code. Velocity separates Java code from the web pages, making the web site more maintainable over the long run and providing a viable alternative to Java Server Pages (JSPs) or PHP.

177 |

Velocity can be used to generate web pages, SQL, PostScript and other output from templates. It can be used either as a standalone utility for generating source code and reports, or as an integrated component of other systems. When complete, Velocity will provide template services for the Turbine web application framework. Velocity+Turbine will provide a template service that will allow web applications to be developed according to a true MVC model.

178 |
179 |
180 |

What can Velocity do for me?

181 |
182 |

The Mud Store Example

183 |

Suppose you are a page designer for an online store that specializes in selling mud. Let's call it "The Online Mud Store". Business is thriving. Customers place orders for various types and quantities of mud. They login to your site using their username and password, which allows them to view their orders and buy more mud. Right now, Terracotta Mud is on sale, which is very popular. A minority of your customers regularly buys Bright Red Mud, which is also on sale, though not as popular and usually relegated to the margin of your web page. Information about each customer is tracked in your database, so one day the question arises, Why not use Velocity to target special deals on mud to the customers who are most interested in those types of mud?

184 |

Velocity makes it easy to customize web pages to your online visitors. As a web site designer at The Mud Room, you want to make the web page that the customer will see after logging into your site.

185 |

You meet with software engineers at your company, and everyone has agreed that $customer will hold information pertaining to the customer currently logged in, that $mudsOnSpecial will be all the types mud on sale at present. The $flogger object contains methods that help with promotion. For the task at hand, let's concern ourselves only with these three references. Remember, you don't need to worry about how the software engineers extract the necessary information from the database, you just need to know that it works. This lets you get on with your job, and lets the software engineers get on with theirs.

186 |

You could embed the following VTL statement in the web page:

187 |
188 |
 189 | <HTML>
 190 | <BODY>
 191 | Hello $customer.Name!
 192 | <table>
 193 | #foreach( $mud in $mudsOnSpecial )
 194 |    #if ( $customer.hasPurchased($mud) )
 195 |       <tr>
 196 |         <td>
 197 |           $flogger.getPromo( $mud )
 198 |         </td>
 199 |       </tr>
 200 |    #end
 201 | #end
 202 | </table>
 203 | 
204 |
205 |

The exact details of the foreach statement will be described in greater depth shortly; what's important is the impact this short script can have on your web site. When a customer with a penchant for Bright Red Mud logs in, and Bright Red Mud is on sale, that is what this customer will see, prominently displayed. If another customer with a long history of Terracotta Mud purchases logs in, the notice of a Terracotta Mud sale will be front and center. The flexibility of Velocity is enormous and limited only by your creativity.

206 |

Documented in the VTL Reference are the many other Velocity elements, which collectively give you the power and flexibility you need to make your web site a web presence. As you get more familiar with these elements, you will begin to unleash the power of Velocity.

207 |
208 |
209 |
210 |

Velocity Template Language (VTL): An Introduction

211 |

The Velocity Template Language (VTL) is meant to provide the easiest, simplest, and cleanest way to incorporate dynamic content in a web page. Even a web page developer with little or no programming experience should soon be capable of using VTL to incorporate dynamic content in a web site.

212 |

VTL uses references to embed dynamic content in a web site, and a variable is one type of reference. Variables are one type of reference that can refer to something defined in the Java code, or it can get its value from a VTL statement in the web page itself. Here is an example of a VTL statement that could be embedded in an HTML document:

213 |
214 |
 215 | #set( $a = "Velocity" )
 216 | 
217 |
218 |

This VTL statement, like all VTL statements, begins with the # character and contains a directive: set. When an online visitor requests your web page, the Velocity Templating Engine will search through your web page to find all # characters, then determine which mark the beginning of VTL statements, and which of the # characters that have nothing to do with VTL.

219 |

The # character is followed by a directive, set. The set directive uses an expression (enclosed in brackets) -- an equation that assigns a value to a variable. The variable is listed on the left hand side and its value on the right hand side; the two are separated by an = character.

220 |

In the example above, the variable is $a and the value is Velocity. This variable, like all references, begins with the $ character. String values are always enclosed in quotes, either single or double quotes. Single quotes will ensure that the quoted value will be assigned to the reference as is. Double quotes allow you to use velocity references and directives to interpolate, such as "Hello $name", where the $name will be replaced by the current value before that string literal is assigned to the left hand side of the =

221 |

The following rule of thumb may be useful to better understand how Velocity works: References begin with $ and are used to get something. Directives begin with # and are used to do something.

222 |

In the example above, #set is used to assign a value to a variable. The variable, $a, can then be used in the template to output "Velocity".

223 |
224 |
225 |

Hello Velocity World!

226 |

Once a value has been assigned to a variable, you can reference the variable anywhere in your HTML document. In the following example, a value is assigned to $foo and later referenced.

227 |
228 |
 229 | <html>
 230 | <body>
 231 | #set( $foo = "Velocity" )
 232 | Hello $foo World!
 233 | </body>
 234 | <html>
 235 | 
236 |
237 |

The result is a web page that prints "Hello Velocity World!".

238 |

To make statements containing VTL directives more readable, we encourage you to start each VTL statement on a new line, although you are not required to do so. The set directive will be revisited in greater detail later on.

239 |
240 |
241 |

Comments

242 |

Comments allows descriptive text to be included that is not placed into the output of the template engine. Comments are a useful way of reminding yourself and explaining to others what your VTL statements are doing, or any other purpose you find useful. Below is an example of a comment in VTL.

243 |
244 |
 245 | ## This is a single line comment.
 246 | 
247 |
248 |

A single line comment begins with ## and finishes at the end of the line. If you're going to write a few lines of commentary, there's no need to have numerous single line comments. Multi-line comments, which begin with #* and end with *#, are available to handle this scenario.

249 |
250 |
 251 | This is text that is outside the multi-line comment.
 252 | Online visitors can see it.
 253 | #*
 254 |  Thus begins a multi-line comment. Online visitors won't
 255 |  see this text because the Velocity Templating Engine will
 256 |  ignore it.
 257 | *#
 258 | Here is text outside the multi-line comment; it is visible.
 259 | 
260 |
261 |

Here are a few examples to clarify how single line and multi-line comments work:

262 |
263 |
 264 | This text is visible. ## This text is not.
 265 | This text is visible.
 266 | This text is visible. #* This text, as part of a multi-line
 267 | comment, is not visible. This text is not visible; it is also
 268 | part of the multi-line comment. This text still not
 269 | visible. *# This text is outside the comment, so it is visible.
 270 | ## This text is not visible.
 271 | 
272 |
273 |

There is a third type of comment, the VTL comment block, which may be used to store such information as the document author and versioning information:

274 |
275 |
 276 | #**
 277 | This is a VTL comment block and
 278 | may be used to store such information
 279 | as the document author and versioning
 280 | information:
 281 | @author
 282 | @version 5
 283 | *#
 284 | 
285 |
286 |
287 |
288 |

References

289 |

There are three types of references in the VTL: variables, properties and methods. As a designer using the VTL, you and your engineers must come to an agreement on the specific names of references so you can use them correctly in your templates.

290 |

Everything coming to and from a reference is treated as a String object. If there is an object that represents $foo (such as an Integer object), then Velocity will call its .toString() method to resolve the object into a String.

291 |

Variables
292 | The shorthand notation of a variable 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:

293 |
    294 |
  • alphabetic (a .. z, A .. Z)
  • 295 |
  • numeric (0 .. 9)
  • 296 |
  • hyphen ("-")
  • 297 |
  • underscore ("_")
  • 298 |
299 |

Here are some examples of valid variable references in the VTL:

300 |
301 |
 302 | $foo
 303 | $mudSlinger
 304 | $mud-slinger
 305 | $mud_slinger
 306 | $mudSlinger1
 307 | 
308 |
309 |

When VTL references a variable, such as $foo, the variable can get its value from either a set directive in the template, or from the Java code. For example, if the Java variable $foo has the value bar at the time the template is requested, bar replaces all instances of $foo on the web page. Alternatively, if I include the statement

310 |
311 |
 312 | #set( $foo = "bar" )
 313 | 
314 |
315 |

The output will be the same for all instances of $foo that follow this directive.

316 |

Properties
317 | The second flavor of VTL references are properties, and properties have a distinctive format. The shorthand notation consists of a leading $ character followed a VTL Identifier, followed by a dot character (".") and another VTL Identifier. These are examples of valid property references in the VTL:

318 |
319 |
 320 | $customer.Address
 321 | $purchase.Total
 322 | 
323 |
324 |

Take the first example, $customer.Address. It can have two meanings. It can mean, Look in the hashtable identified as customer and return the value associated with the key Address. But $customer.Address can also be referring to a method (references that refer to methods will be discussed in the next section); $customer.Address could be an abbreviated way of writing $customer.getAddress(). When your page is requested, Velocity will determine which of these two possibilities makes sense, and then return the appropriate value.

325 |

Methods
326 | A method is defined in the Java code and is capable of doing something useful, like running a calculation or arriving at a decision. Methods are references that 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 (")"). These are examples of valid method references in the VTL:

327 |
328 |
 329 | $customer.getAddress()
 330 | $purchase.getTotal()
 331 | $page.setTitle( "My Home Page" )
 332 | $person.setAttributes( ["Strange", "Weird", "Excited"] )
 333 | $person.setAttributes( ["Strange", "(Weird)", "[Excited]"] )
 334 | 
335 |
336 |

The first two examples -- $customer.getAddress() and $purchase.getTotal() -- may look similar to those used in the Properties section above, $customer.Address and $purchase.Total. If you guessed that these examples must be related some in some fashion, you are correct!

337 |

VTL Properties can be used as a shorthand notation for VTL Methods. The Property $customer.Address has the exact same effect as using the Method $customer.getAddress(). It is generally preferable to use a Property when available. The main difference between Properties and Methods is that you can specify a parameter list to a Method.

338 |

The shorthand notation can be used for the following Methods

339 |
340 |
 341 | $sun.getPlanets()
 342 | $annelid.getDirt()
 343 | $album.getPhoto()
 344 | 
345 |
346 |

We might expect these methods to return the names of planets belonging to the sun, feed our earthworm, or get a photograph from an album. Only the long notation works for the following Methods.

347 |
348 |
 349 | $sun.getPlanet( ["Earth", "Mars", "Neptune"] )
 350 | ## Can't pass a parameter list with $sun.Planets
 351 | $sisyphus.pushRock()
 352 | ## Velocity assumes I mean $sisyphus.getRock()
 353 | $book.setTitle( "Homage to Catalonia" )
 354 | ## Can't pass a parameter list
 355 | 
356 |
357 |

Property Lookup Rules
358 | As was mentioned earlier, properties often refer to methods of the parent object. Velocity is quite clever when figuring out which method corresponds to a requested property. It tries out different alternatives based on several established naming conventions. The exact lookup sequence depends on whether or not the property name starts with an upper-case letter. For lower-case names, such as $customer.address, the sequence is

359 |
    360 |
  1. getaddress()
  2. 361 |
  3. getAddress()
  4. 362 |
  5. get("address")
  6. 363 |
  7. isAddress()
  8. 364 |
For upper-case property names like $customer.Address, it is slightly different: 365 |
    366 |
  1. getAddress()
  2. 367 |
  3. getaddress()
  4. 368 |
  5. get("Address")
  6. 369 |
  7. isAddress()
  8. 370 |
371 |

Formal Reference Notation
372 | Shorthand notation for references was used for the examples listed above, but there is also a formal notation for references, which is demonstrated below:

373 |
374 |
 375 | ${mudSlinger}
 376 | ${customer.Address}
 377 | ${customer.Address.Address}
 378 | ${customer.Address.Address.Address()}
 379 | ${purchase.getTotal()}
 380 | 
381 |
382 |

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

383 |

Suppose you were constructing a sentence on the fly where $vice was to be used as the base word in the noun of a sentence. The goal is to allow someone to choose the base word and produce one of the two following results: "Jack is a pyromaniac." or "Jack is a kleptomaniac.". Using the shorthand notation would be inadequate for this task. Consider the following example:

384 |
385 |
 386 | Jack is a $vicemaniac.
 387 | 
388 |
389 |

There is ambiguity here, and Velocity assumes that $vicemaniac, not $vice, is the Identifier that you mean to use. Finding no value for $vicemaniac, it will return $vicemaniac. Using formal notation can resolve this problem.

390 |
391 |
 392 | Jack is a ${vice}maniac.
 393 | 
394 |
395 |

Now Velocity knows that $vice, not $vicemaniac, is the reference. Formal notation is often useful when references are directly adjacent to text in a template.

396 |

Quiet Reference Notation
397 | When Velocity encounters an undefined reference, its normal behavior is to output the image of the reference. For example, suppose the following reference appears as part of a VTL template.

398 |
399 |
 400 | <input type="text" name="email" value="$email"/>
 401 | 
402 |
403 |

When the form initially loads, the variable reference $email has no value, but you prefer a blank text field to one with a value of "$email". Using the quiet reference notation circumvents Velocity's normal behavior; instead of using $email in the VTL you would use $!email. So the above example would look like the following:

404 |
405 |
 406 | <input type="text" name="email" value="$!email"/>
 407 | 
408 |
409 |

Now when the form is initially loaded and $email still has no value, an empty string will be output instead of "$email".

410 |

Formal and quiet reference notation can be used together, as demonstrated below.

411 |
412 |
 413 | <input type="text" name="email" value="$!{email}"/>
 414 | 
415 |
416 |
417 |
418 |

Getting literal

419 |

VTL uses special characters, such as $ and #, to do its work, so some added care should be taken where using these characters in your templates. This section deals with escaping the $ character.

420 |

Currency
421 | There is no problem writing "I bought a 4 lb. sack of potatoes at the farmer's market for only $2.50!" As mentioned, a VTL identifier always begins with an upper- or lowercase letter, so $2.50 would not be mistaken for a reference.

422 |

Escaping Valid VTL References
423 | Cases may arise where there is the potential for Velocity to get confused. Escaping special characters is the best way to handle VTL's special characters in your templates, and this can be done using the backslash ( \ ) character.

424 |
425 |
 426 | #set( $email = "foo" )
 427 | $email
 428 | 
429 |
430 |

If Velocity encounters a reference in your VTL template to $email, it will search the Context for a corresponding value. Here the output will be foo, because $email is defined. If $email is not defined, the output will be $email.

431 |

Suppose that $email is defined (for example, if it has the value foo), and that you want to output $email. There are a few ways of doing this, but the simplest is to use the escape character.

432 |
433 |
 434 | ## The following line defines $email in this template:
 435 | #set( $email = "foo" )
 436 | $email
 437 | \$email
 438 | \\$email
 439 | \\\$email
 440 | 
441 |
442 |

renders as

443 |
444 |
 445 | foo
 446 | $email
 447 | \foo
 448 | \$email
 449 | 
450 |
451 |

Note that the \ character bind to the $ from the left. The bind-from-left rule causes \\\$email to render as \\$email. Compare these examples to those in which $email is not defined.

452 |
453 |
 454 | $email
 455 | \$email
 456 | \\$email
 457 | \\\$email
 458 | 
459 |
460 |

renders as

461 |
462 |
 463 | $email
 464 | \$email
 465 | \\$email
 466 | \\\$email
 467 | 
468 |
469 |

Notice Velocity handles references that are defined differently from those that have not been defined. Here is a set directive that gives $foo the value gibbous.

470 |
471 |
 472 | #set( $foo = "gibbous" )
 473 | $moon = $foo
 474 | 
475 |
476 |

The output will be: $moon = gibbous -- where $moon is output as a literal because it is undefined and gibbous is output in place of $foo.

477 |

It is also possible to escape VTL directives; this is described in more detail in the Directives section.

478 |
479 |
480 |

Case Substitution

481 |

Now that you are familiar with references, you can begin to apply them effectively in your templates. Velocity references take advantage of some Java principles that template designers will find easy to use. For example:

482 |
483 |
 484 | $foo
 485 | $foo.getBar()
 486 | ## is the same as
 487 | $foo.Bar
 488 | $data.setUser("jon")
 489 | ## is the same as
 490 | #set( $data.User = "jon" )
 491 | $data.getRequest().getServerName()
 492 | ## is the same as
 493 | $data.Request.ServerName
 494 | ## is the same as
 495 | ${data.Request.ServerName}
 496 | 
497 |
498 |

These examples illustrate alternative uses for the same references. Velocity takes advantage of Java's introspection and bean features to resolve the reference names to both objects in the Context as well as the objects methods. It is possible to embed and evaluate references almost anywhere in your template.

499 |

Velocity, which is modelled on the Bean specifications defined by Sun Microsystems, is case sensitive; however, its developers have strove to catch and correct user errors wherever possible. When the method getFoo() is referred to in a template by $bar.foo, Velocity will first try $getfoo. If this fails, it will then try $getFoo. Similarly, when a template refers to $bar.Foo, Velocity will try $getFoo() first and then try getfoo().

500 |

Note: References to instance variables in a template are not resolved. Only references to the attribute equivalents of JavaBean getter/setter methods are resolved (i.e. $foo.Name does resolve to the class Foo's getName() instance method, but not to a public Name instance variable of Foo).

501 |
502 |
503 |

Directives

504 |

References allow template designers to generate dynamic content for web sites, while directives -- easy to use script elements that can be used to creatively manipulate the output of Java code -- permit web designers to truly take charge of the appearance and content of the web site.

505 |

Directives always begin with a #. Like references, the name of the directive may be bracketed by a { and a } symbol. This is useful with directives that are immediately followed by text. For example the following produces an error:

506 |
507 |
 508 | #if($a==1)true enough#elseno way!#end
 509 | 
510 |
511 |

In such a case, use the brackets to separate #else from the rest of the line.

512 |
513 |
 514 | #if($a==1)true enough#{else}no way!#end
 515 | 
516 |
#set 517 |

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, and this occurs in brackets, as demonstrated:

518 |
519 |
 520 | #set( $primate = "monkey" )
 521 | #set( $customer.Behavior = $primate )
 522 | 
523 |
524 |

The left hand side (LHS) of the assignment must be a variable reference or a property reference. The right hand side (RHS) can be one of the following types:

525 |
    526 |
  • Variable reference
  • 527 |
  • String literal
  • 528 |
  • Property reference
  • 529 |
  • Method reference
  • 530 |
  • Number literal
  • 531 |
  • ArrayList
  • 532 |
  • Map
  • 533 |
534 |

These examples demonstrate each of the aforementioned types:

535 |
536 |
 537 | #set( $monkey = $bill ) ## variable reference
 538 | #set( $monkey.Friend = "monica" ) ## string literal
 539 | #set( $monkey.Blame = $whitehouse.Leak ) ## property reference
 540 | #set( $monkey.Plan = $spindoctor.weave($web) ) ## method reference
 541 | #set( $monkey.Number = 123 ) ##number literal
 542 | #set( $monkey.Say = ["Not", $my, "fault"] ) ## ArrayList
 543 | #set( $monkey.Map = {"banana" : "good", "roast beef" : "bad"}) ## Map
 544 | 
545 |
546 |

NOTE: For the ArrayList example the elements defined with the [..] operator are accessible using the methods defined in the ArrayList class. So, for example, you could access the first element above using $monkey.Say.get(0).

547 |

Similarly, for the Map example, the elements defined within the { } operator are accessible using the methods defined in the Map class. So, for example, you could access the first element above using $monkey.Map.get("bannana") to return a String 'good', or even $monkey.Map.banana to return the same value.

548 |

The RHS can also be a simple arithmetic expression:

549 |
550 |
 551 | #set( $value = $foo + 1 )
 552 | #set( $value = $bar - 1 )
 553 | #set( $value = $foo * $bar )
 554 | #set( $value = $foo / $bar )
 555 | 
556 |
557 |

If the RHS is a property or method reference that evaluates to null, it will not be assigned to the LHS. Depending on how Velocity is configured, it is usually not possible to remove an existing reference from the context via this mechanism. (Note that this can be permitted by changing one of the Velocity configuration properties). This can be confusing for newcomers to Velocity. For example:

558 |
559 |
 560 | #set( $result = $query.criteria("name") )
 561 | The result of the first query is $result
 562 | #set( $result = $query.criteria("address") )
 563 | The result of the second query is $result
 564 | 
565 |
566 |

If $query.criteria("name") returns the string "bill", and $query.criteria("address") returns null, the above VTL will render as the following:

567 |
568 |
 569 | The result of the first query is bill
 570 | The result of the second query is bill
 571 | 
572 |
573 |

This tends to confuse newcomers who construct #foreach loops that attempt to #set a reference via a property or method reference, then immediately test that reference with an #if directive. For example:

574 |
575 |
 576 | #set( $criteria = ["name", "address"] )
 577 | #foreach( $criterion in $criteria )
 578 |     #set( $result = $query.criteria($criterion) )
 579 |     #if( $result )
 580 |         Query was successful
 581 |     #end
 582 | #end
 583 | 
584 |
585 |

In the above example, it would not be wise to rely on the evaluation of $result to determine if a query was successful. After $result has been #set (added to the context), it cannot be set back to null (removed from the context). The details of the #if and #foreach directives are covered later in this document.

586 |

One solution to this would be to pre-set $result to false. Then if the $query.criteria() call fails, you can check.

587 |
588 |
 589 | #set( $criteria = ["name", "address"] )
 590 | #foreach( $criterion in $criteria )
 591 |     #set( $result = false )
 592 |     #set( $result = $query.criteria($criterion) )
 593 |     #if( $result )
 594 |         Query was successful
 595 |     #end
 596 | #end
 597 | 
598 |
599 |

Unlike some of the other Velocity directives, the #set directive does not have an #end statement.

Literals 600 |

When using the #set directive, string literals that are enclosed in double quote characters will be parsed and rendered, as shown:

601 |
602 |
 603 | #set( $directoryRoot = "www" )
 604 | #set( $templateName = "index.vm" )
 605 | #set( $template = "$directoryRoot/$templateName" )
 606 | $template
 607 | 
608 |
609 |

The output will be

610 |
611 |
 612 | www/index.vm
 613 | 
614 |
615 |

However, when the string literal is enclosed in single quote characters, it will not be parsed:

616 |
617 |
 618 | #set( $foo = "bar" )
 619 | $foo
 620 | #set( $blargh = '$foo' )
 621 | $blargh
 622 | 
623 |
This renders as: 624 |
625 |
 626 |   bar
 627 |   $foo
 628 | 
629 |
630 |

By default, this feature of using single quotes to render unparsed text is available in Velocity. This default can be changed by editing velocity.properties such that stringliterals.interpolate=false.

631 |

Alternately, the #literal script element allows the template designer to easily use large chunks of uninterpreted content in VTL code. This can be especially useful in place of escaping multiple directives.

632 |
633 |
 634 | #literal()
 635 | #foreach ($woogie in $boogie)
 636 |   nothing will happen to $woogie
 637 | #end
 638 | #end
 639 | 
640 |
641 |

Renders as:

642 |
643 |
 644 | #foreach ($woogie in $boogie)
 645 |   nothing will happen to $woogie
 646 | #end
 647 | 
648 |
649 |
650 |
651 |

Conditionals

If / ElseIf / Else 652 |

The #if directive in Velocity allows for text to be included when the web page is generated, on the conditional that the if statement is true. For example:

653 |
654 |
 655 | #if( $foo )
 656 |    <strong>Velocity!</strong>
 657 | #end
 658 | 
659 |
660 |

The variable $foo is evaluated to determine whether it is true, which will happen under one of two circumstances: (i) $foo is a boolean (true/false) which has a true value, or (ii) the value is not null. Remember that the Velocity context only contains Objects, so when we say 'boolean', it will be represented as a Boolean (the class). This is true even for methods that return boolean - the introspection infrastructure will return a Boolean of the same logical value.

661 |

The content between the #if and the #end statements become the output if the evaluation is true. In this case, if $foo is true, the output will be: "Velocity!". Conversely, if $foo has a null value, or if it is a boolean false, the statement evaluates as false, and there is no output.

662 |

An #elseif or #else element can be used with an #if element. Note that the Velocity Templating Engine will stop at the first expression that is found to be true. In the following example, suppose that $foo has a value of 15 and $bar has a value of 6.

663 |
664 |
 665 | #if( $foo < 10 )
 666 |     <strong>Go North</strong>
 667 | #elseif( $foo == 10 )
 668 |     <strong>Go East</strong>
 669 | #elseif( $bar == 6 )
 670 |     <strong>Go South</strong>
 671 | #else
 672 |     <strong>Go West</strong>
 673 | #end
 674 | 
675 |
676 |

In this example, $foo is greater than 10, so the first two comparisons fail. Next $bar is compared to 6, which is true, so the output is Go South.

677 |

Relational and Logical Operators

678 |

Velocity uses the equivalent operator to determine the relationships between variables. Here is a simple example to illustrate how the equivalent operator is used.

679 |
680 |
 681 | #set ($foo = "deoxyribonucleic acid")
 682 | #set ($bar = "ribonucleic acid")
 683 | #if ($foo == $bar)
 684 |   In this case it's clear they aren't equivalent. So...
 685 | #else
 686 |   They are not equivalent and this will be the output.
 687 | #end
 688 | 
689 |
690 |

Note that the semantics of == are slightly different than Java where == can only be used to test object equality. In Velocity the equivalent operator can be used to directly compare numbers, strings, or objects. When the objects are of different classes, the string representations are obtained by calling toString() for each object and then compared.

691 |

Velocity has logical AND, OR and NOT operators as well. For further information, please see the VTL Reference Guide Below are examples demonstrating the use of the logical AND, OR and NOT operators.

692 |
693 |
 694 | ## logical AND
 695 | #if( $foo && $bar )
 696 |    <strong> This AND that</strong>
 697 | #end
 698 | 
699 |
700 |

The #if() directive will only evaluate to true if both $foo and $bar are true. If $foo is false, the expression will evaluate to false; $bar will not be evaluated. If $foo is true, the Velocity Templating Engine will then check the value of $bar; if $bar is true, then the entire expression is true and This AND that becomes the output. If $bar is false, then there will be no output as the entire expression is false.

701 |

Logical OR operators work the same way, except only one of the references need evaluate to true in order for the entire expression to be considered true. Consider the following example.

702 |
703 |
 704 | ## logical OR
 705 | #if( $foo || $bar )
 706 |     <strong>This OR That</strong>
 707 | #end
 708 | 
709 |
710 |

If $foo is true, the Velocity Templating Engine has no need to look at $bar; whether $bar is true or false, the expression will be true, and This OR That will be output. If $foo is false, however, $bar must be checked. In this case, if $bar is also false, the expression evaluates to false and there is no output. On the other hand, if $bar is true, then the entire expression is true, and the output is This OR That

711 |

With logical NOT operators, there is only one argument :

712 |
713 |
 714 | ##logical NOT
 715 | #if( !$foo )
 716 |   <strong>NOT that</strong>
 717 | #end
 718 | 
719 |
720 |

Here, the if $foo is true, then !$foo evaluates to false, and there is no output. If $foo is false, then !$foo evaluates to true and NOT that will be output. Be careful not to confuse this with the quiet reference $!foo which is something altogether different.

721 |

There are text versions of all logical operators, including eq, ne, and, or, not, gt, ge, lt, and le.

722 |

One more useful note. When you wish to include text immediately following a #else directive you will need to use curly brackets immediately surrounding the directive to differentiate it from the following text. (Any directive can be delimited by curly brackets, although this is most useful for #else).

723 |
724 |
 725 | #if( $foo == $bar)it's true!#{else}it's not!#end</li>
 726 | 
727 |
728 |
729 |
730 |

Loops

Foreach Loop 731 |

The #foreach element allows for looping. For example:

732 |
733 |
 734 | <ul>
 735 | #foreach( $product in $allProducts )
 736 |     <li>$product</li>
 737 | #end
 738 | </ul>
 739 | 
740 |
741 |

This #foreach loop causes the $allProducts list (the object) to be looped over for all of the products (targets) in the list. Each time through the loop, the value from $allProducts is placed into the $product variable.

742 |

The contents of the $allProducts variable is a Vector, a Hashtable or an Array. The value assigned to the $product variable is a Java Object and can be referenced from a variable as such. For example, if $product was really a Product class in Java, its name could be retrieved by referencing the $product.Name method (ie: $Product.getName()).

743 |

Lets say that $allProducts is a Hashtable. If you wanted to retrieve the key values for the Hashtable as well as the objects within the Hashtable, you can use code like this:

744 |
745 |
 746 | <ul>
 747 | #foreach( $key in $allProducts.keySet() )
 748 |     <li>Key: $key -> Value: $allProducts.get($key)</li>
 749 | #end
 750 | </ul>
 751 | 
752 |
753 |

Velocity provides an easy way to get the loop counter so that you can do something like the following:

754 |
755 |
 756 | <table>
 757 | #foreach( $customer in $customerList )
 758 |     <tr><td>$velocityCount</td><td>$customer.Name</td></tr>
 759 | #end
 760 | </table>
 761 | 
762 |
763 |

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. Here's what the loop counter properties section of the velocity.properties file appears:

764 |
765 |
 766 | # Default name of the loop counter
 767 | # variable reference.
 768 | directive.foreach.counter.name = velocityCount
 769 | # Default starting value of the loop
 770 | # counter variable reference.
 771 | directive.foreach.counter.initial.value = 1
 772 | 
773 |
774 |

It's possible to set a maximum allowed number of times that a loop may be executed. By default there is no max (indicated by a value of 0 or less), but this can be set to an arbitrary number in the velocity.properties file. This is useful as a fail-safe.

775 |
776 |
 777 | # The maximum allowed number of loops.
 778 | directive.foreach.maxloops = -1
 779 | 
780 |
781 |
782 |
783 |

Include

784 |

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.

785 |
786 |
 787 | #include( "one.txt" )
 788 | 
789 |
790 |

The file to which the #include directive refers is enclosed in quotes. If more than one file will be included, they should be separated by commas.

791 |
792 |
 793 | #include( "one.gif","two.txt","three.htm" )
 794 | 
795 |
796 |

The file being included need not be referenced by name; in fact, it is often preferable to use a variable instead of a filename. This could be useful for targeting output according to criteria determined when the page request is submitted. Here is an example showing both a filename and a variable.

797 |
798 |
 799 | #include( "greetings.txt", $seasonalstock )
 800 | 
801 |
802 |
803 |
804 |

Parse

805 |

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.

806 |
807 |
 808 | #parse( "me.vm" )
 809 | 
810 |
811 |

Like the #include directive, #parse can take a variable rather than a template. Any templates to which #parse refers must be included under TEMPLATE_ROOT. Unlike the #include directive, #parse will only take a single argument.

812 |

VTL templates can have #parse statements referring to templates that in turn have #parse statements. By default set to 10, the directive.parse.max.depth line of the velocity.properties allows users to customize maximum number of #parse referrals that can occur from a single template. (Note: If the directive.parse.max.depth property is absent from the velocity.properties file, Velocity will set this default to 10.) Recursion is permitted, for example, if the template dofoo.vm contains the following lines:

813 |
814 |
 815 | Count down.
 816 | #set( $count = 8 )
 817 | #parse( "parsefoo.vm" )
 818 | All done with dofoo.vm!
 819 | 
820 |
821 |

It would reference the template parsefoo.vm, which might contain the following VTL:

822 |
823 |
 824 | $count
 825 | #set( $count = $count - 1 )
 826 | #if( $count > 0 )
 827 |     #parse( "parsefoo.vm" )
 828 | #else
 829 |     All done with parsefoo.vm!
 830 | #end
 831 | 
832 |
833 |

After "Count down." is displayed, Velocity passes through parsefoo.vm, counting down from 8. When the count reaches 0, it will display the "All done with parsefoo.vm!" message. At this point, Velocity will return to dofoo.vm and output the "All done with dofoo.vm!" message.

834 |
835 |
836 |

Stop

837 |

The #stop script element prevents any further text or references in the page from being rendered. This is useful for debugging purposes.

838 |
839 |
840 |

Evaluate

841 |

The #evaluate directive can be used to dynamically evaluate VTL. This allows the template to evaluate a string that is created at render time. Such a string might be used to internationalize the template or to include parts of a template from a database.

842 |

The example below will display abc.

843 |
844 |
 845 | #set($source1 = "abc")
 846 | #set($select = "1")
 847 | #set($dynamicsource = "$source$select")
 848 | #evaluate($dynamicsource)
 849 | 
850 |
851 |
852 |
853 |

Velocimacros

854 |

The #macro script element allows template designers to define a repeated segment of a VTL template. Velocimacros are very useful in a wide range of scenarios both simple and complex. This Velocimacro, created for the sole purpose of saving keystrokes and minimizing typographic errors, provides an introduction to the concept of Velocimacros.

855 |
856 |
 857 | #macro( d )
 858 | <tr><td></td></tr>
 859 | #end
 860 | 
861 |
862 |

The Velocimacro being defined in this example is d, and it can be called in a manner analogous to any other VTL directive:

863 |
864 |
 865 | #d()
 866 | 
867 |
868 |

When this template is called, Velocity would replace #d() with a row containing a single, empty data cell.

869 |

A Velocimacro could take any number of arguments -- even zero arguments, as demonstrated in the first example, is an option -- but when the Velocimacro is invoked, it must be called with the same number of arguments with which it was defined. Many Velocimacros are more involved than the one defined above. Here is a Velocimacro that takes two arguments, a color and an array.

870 |
871 |
 872 | #macro( tablerows $color $somelist )
 873 | #foreach( $something in $somelist )
 874 |     <tr><td bgcolor=$color>$something</td></tr>
 875 | #end
 876 | #end
 877 | 
878 |
879 |

The Velocimacro being defined in this example, tablerows, takes two arguments. The first argument takes the place of $color, and the second argument takes the place of $somelist.

880 |

Anything that can be put into a VTL template can go into the body of a Velocimacro. The tablerows Velocimacro is a foreach statement. There are two #end statements in the definition of the #tablerows Velocimacro; the first belongs to the #foreach, the second ends the Velocimacro definition.

881 |
882 |
 883 | #set( $greatlakes = ["Superior","Michigan","Huron","Erie","Ontario"] )
 884 | #set( $color = "blue" )
 885 | <table>
 886 |     #tablerows( $color $greatlakes )
 887 | </table>
 888 | 
889 |
890 |

Notice that $greatlakes takes the place of $somelist. When the #tablerows Velocimacro is called in this situation, the following output is generated:

891 |
892 |
 893 | <table>
 894 |     <tr><td bgcolor="blue">Superior</td></tr>
 895 |     <tr><td bgcolor="blue">Michigan</td></tr>
 896 |     <tr><td bgcolor="blue">Huron</td></tr>
 897 |     <tr><td bgcolor="blue">Erie</td></tr>
 898 |     <tr><td bgcolor="blue">Ontario</td></tr>
 899 | </table>
 900 | 
901 |
902 |

Velocimacros can be defined inline in a Velocity template, meaning that it is unavailable to other Velocity templates on the same web site. Defining a Velocimacro such that it can be shared by all templates has obvious advantages: it reduces the need to redefine the Velocimacro on numerous templates, saving work and reducing the chance of error, and ensures that a single change to a macro available to more than one template.

903 |

Were the #tablerows($color $list) Velocimacro defined in a Velocimacros template library, this macro could be used on any of the regular templates. It could be used many times and for many different purposes. In the template mushroom.vm devoted to all things fungi, the #tablerows Velocimacro could be invoked to list the parts of a typical mushroom:

904 |
905 |
 906 | #set( $parts = ["volva","stipe","annulus","gills","pileus"] )
 907 | #set( $cellbgcol = "#CC00FF" )
 908 | <table>
 909 | #tablerows( $cellbgcol $parts )
 910 | </table>
 911 | 
912 |
913 |

When fulfilling a request for mushroom.vm, Velocity would find the #tablerows Velocimacro in the template library (defined in the velocity.properties file) and generate the following output:

914 |
915 |
 916 | <table>
 917 |     <tr><td bgcolor="#CC00FF">volva</td></tr>
 918 |     <tr><td bgcolor="#CC00FF">stipe</td></tr>
 919 |     <tr><td bgcolor="#CC00FF">annulus</td></tr>
 920 |     <tr><td bgcolor="#CC00FF">gills</td></tr>
 921 |     <tr><td bgcolor="#CC00FF">pileus</td></tr>
 922 | </table>
 923 | 
924 |
Velocimacro Arguments 925 |

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

926 |
    927 |
  • Reference : anything that starts with '$'
  • 928 |
  • String literal : something like "$foo" or 'hello'
  • 929 |
  • Number literal : 1, 2 etc
  • 930 |
  • IntegerRange : [ 1..2] or [$foo .. $bar]
  • 931 |
  • ObjectArray : [ "a", "b", "c"]
  • 932 |
  • boolean value true
  • 933 |
  • boolean value false
  • 934 |
935 |

When passing references as arguments to Velocimacros, please note that references are passed 'by name'. This means that their value is 'generated' at each use inside the Velocimacro. This feature allows you to pass references with method calls and have the method called at each use. For example, when calling the following Velocimacro as shown

936 |
937 |
 938 |      #macro( callme $a )
 939 |          $a $a $a
 940 |      #end
 941 |      #callme( $foo.bar() )
 942 | 
943 |
944 |

results in the method bar() of the reference $foo being called 3 times.

945 |

At first glance, this feature appears surprising, but when you take into consideration the original motivation behind Velocimacros -- to eliminate cut'n'paste duplication of commonly used VTL -- it makes sense. It allows you to do things like pass stateful objects, such as an object that generates colors in a repeating sequence for coloring table rows, into the Velocimacro.

946 |

If you need to circumvent this feature, you can always just get the value from the method as a new reference and pass that :

947 |
948 |
 949 |      #set( $myval = $foo.bar() )
 950 |      #callme( $myval )
 951 | 
952 |
Velocimacro Properties 953 |

Several lines in the velocity.properties file allow for flexible implementation of Velocimacros. Note that these are also documented in the Developer Guide.

954 |

velocimacro.library - A comma-separated list of all Velocimacro template libraries. By default, Velocity looks for a single library: VM_global_library.vm. The configured template path is used to find the Velocimacro libraries.

955 |

velocimacro.permissions.allow.inline - This property, which has possible values of true or false, determines whether Velocimacros can be defined in regular templates. The default, true, allows template designers to define Velocimacros in the templates themselves.

956 |

velocimacro.permissions.allow.inline.to.replace.global - With possible values of true or false, this property allows the user to specify if a Velocimacro defined inline in a template can replace a globally defined template, one that was loaded on startup via the velocimacro.library property. The default, false, prevents Velocimacros defined inline in a template from replacing those defined in the template libraries loaded at startup.

957 |

velocimacro.permissions.allow.inline.local.scope - This property, with possible values of true or false, defaulting to false, controls if Velocimacros defined inline are 'visible' only to the defining template. In other words, with this property set to true, a template can define inline VMs that are usable only by the defining template. You can use this for fancy VM tricks - if a global VM calls another global VM, with inline scope, 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.

958 |

velocimacro.context.localscope - This property has the possible values true or false, and the default is false. When true, any modifications to the context via #set() within a Velocimacro are considered 'local' to the Velocimacro, and will not permanently affect the context.

959 |

velocimacro.library.autoreload - This property controls Velocimacro library autoloading. The default value is false. When set to true the source Velocimacro library for an invoked Velocimacro will be checked for changes, and reloaded if necessary. This allows you to change and test Velocimacro libraries without having to restart your application or servlet container, just like you can with regular templates. This mode only works when caching is off in the resource loaders (e.g. file.resource.loader.cache = false ). This feature is intended for development, not for production.

Velocimacro Trivia 960 |

Currently, Velocimacros must be defined before they are first used in a template. This means that your #macro() declarations should come before using the Velocimacros.

961 |

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. To get around this, simply use the velocimacro.library facility to have Velocity load your VMs at startup.

962 |
963 |
964 |

Escaping VTL Directives

965 |

VTL directives can be escaped with the backslash character ("\") in a manner similar to valid VTL references.

966 |
967 |
 968 | ## #include( "a.txt" ) renders as <contents of a.txt>
 969 | #include( "a.txt" )
 970 | ## \#include( "a.txt" ) renders as #include( "a.txt" )
 971 | \#include( "a.txt" )
 972 | ## \\#include ( "a.txt" ) renders as \<contents of a.txt>
 973 | \\#include ( "a.txt" )
 974 | 
975 |
976 |

Extra care should be taken when escaping VTL directives that contain multiple script elements in a single directive (such as in an if-else-end statements). Here is a typical VTL if-statement:

977 |
978 |
 979 | #if( $jazz )
 980 |     Vyacheslav Ganelin
 981 | #end
 982 | 
983 |
984 |

If $jazz is true, the output is

985 |
986 |
 987 | Vyacheslav Ganelin
 988 | 
989 |
990 |

If $jazz is false, there is no output. Escaping script elements alters the output. Consider the following case:

991 |
992 |
 993 | \#if( $jazz )
 994 |     Vyacheslav Ganelin
 995 | \#end
 996 | 
997 |
998 |

Whether $jazz is true or false, the output will be

999 |
1000 |
1001 |  #if($ jazz )
1002 |      Vyacheslav Ganelin
1003 |  #end
1004 | 
1005 |
1006 |

In fact, because all script elements are escaped, $jazz is never evaluated for its boolean value. Suppose backslashes precede script elements that are legitimately escaped:

1007 |
1008 |
1009 | \\#if( $jazz )
1010 |    Vyacheslav Ganelin
1011 | \\#end
1012 | 
1013 |
1014 |

In this case, if $jazz is true, the output is

1015 |
1016 |
1017 | \ Vyacheslav Ganelin
1018 | \
1019 | 
1020 |
1021 |

To understand this, note that the #if( arg ) when ended by a newline (return) will omit the newline from the output. Therefore, the body of the #if() block follows the first '\', rendered from the '\\' preceding the #if(). The last \ is on a different line than the text because there is a newline after 'Ganelin', so the final \\, preceding the #end is part of the body of the block.

1022 |

If $jazz is false, the output is

1023 |
1024 |
1025 | \
1026 | 
1027 |
1028 |

Note that things start to break if script elements are not properly escaped.

1029 |
1030 |
1031 | \\\#if( $jazz )
1032 |     Vyacheslave Ganelin
1033 | \\#end
1034 | 
1035 |
1036 |

Here the #if is escaped, but there is an #end remaining; having too many endings will cause a parsing error.

1037 |
1038 |
1039 |

VTL: Formatting Issues

1040 |

Although VTL in this user guide is often displayed with newlines and whitespaces, the VTL shown below

1041 |
1042 |
1043 | #set( $imperial = ["Munetaka","Koreyasu","Hisakira","Morikune"] )
1044 | #foreach( $shogun in $imperial )
1045 |     $shogun
1046 | #end
1047 | 
1048 |
1049 |

is equally valid as the following snippet that Geir Magnusson Jr. posted to the Velocity user mailing list to illustrate a completely unrelated point:

1050 |
1051 |
1052 | Send #set($foo=["$10 and ","a pie"])#foreach($a in $foo)$a#end please.
1053 | 
1054 |
1055 |

Velocity's behaviour is to gobble up excess whitespace. The preceding directive can be written as:

1056 |
1057 |
1058 | Send me
1059 | #set( $foo = ["$10 and ","a pie"] )
1060 | #foreach( $a in $foo )
1061 | $a
1062 | #end
1063 | please.
1064 | 
1065 |
1066 |

or as

1067 |
1068 |
1069 | Send me
1070 | #set($foo       = ["$10 and ","a pie"])
1071 |                  #foreach           ($a in $foo )$a
1072 |          #end please.
1073 | 
1074 |
1075 |

In each case the output will be the same.

1076 |
1077 |
1078 |

Other Features and Miscellany

1079 |
1080 |

Math

1081 |

Velocity has a handful of built-in mathematical functions that can be used in templates with the set directive. The following equations are examples of addition, subtraction, multiplication and division, respectively:

1082 |
1083 |
1084 | #set( $foo = $bar + 3 )
1085 | #set( $foo = $bar - 4 )
1086 | #set( $foo = $bar * 6 )
1087 | #set( $foo = $bar / 2 )
1088 | 
1089 |
1090 |

When a division operation is performed between two integers, the result will be an integer. Any remainder can be obtained by using the modulus (%) operator.

1091 |
1092 |
1093 | #set( $foo = $bar % 5 )
1094 | 
1095 |
1096 |
1097 |
1098 |

Range Operator

1099 |

The range operator can be used in conjunction with #set and #foreach statements. Useful for its ability to produce an object array containing integers, the range operator has the following construction:

1100 |
1101 |
1102 | [n..m]
1103 | 
1104 |
1105 |

Both n and m must either be or produce integers. Whether m is greater than or less than n will not matter; in this case the range will simply count down. Examples showing the use of the range operator as provided below:

1106 |
1107 |
1108 | First example:
1109 | #foreach( $foo in [1..5] )
1110 | $foo
1111 | #end
1112 | Second example:
1113 | #foreach( $bar in [2..-2] )
1114 | $bar
1115 | #end
1116 | Third example:
1117 | #set( $arr = [0..1] )
1118 | #foreach( $i in $arr )
1119 | $i
1120 | #end
1121 | Fourth example:
1122 | [1..3]
1123 | 
1124 |
1125 |

Produces the following output:

1126 |
1127 |
1128 | First example:
1129 | 1 2 3 4 5
1130 | Second example:
1131 | 2 1 0 -1 -2
1132 | Third example:
1133 | 0 1
1134 | Fourth example:
1135 | [1..3]
1136 | 
1137 |
1138 |

Note that the range operator only produces the array when used in conjunction with #set and #foreach directives, as demonstrated in the fourth example.

1139 |

Web page designers concerned with making tables a standard size, but where some will not have enough data to fill the table, will find the range operator particularly useful.

1140 |
1141 |
1142 |

Advanced Issues: Escaping and !

1143 |

When a reference is silenced with the ! character and the ! character preceded by an \ escape character, the reference is handled in a special way. Note the differences between regular escaping, and the special case where \ precedes ! follows it:

1144 |
1145 |
1146 | #set( $foo = "bar" )
1147 | $\!foo
1148 | $\!{foo}
1149 | $\\!foo
1150 | $\\\!foo
1151 | 
1152 |
1153 |

This renders as:

1154 |
1155 |
1156 | $!foo
1157 | $!{foo}
1158 | $\!foo
1159 | $\\!foo
1160 | 
1161 |
1162 |

Contrast this with regular escaping, where \ precedes $:

1163 |
1164 |
1165 | \$foo
1166 | \$!foo
1167 | \$!{foo}
1168 | \\$!{foo}
1169 | 
1170 |
1171 |

This renders as:

1172 |
1173 |
1174 | $foo
1175 | $!foo
1176 | $!{foo}
1177 | \bar
1178 | 
1179 |
1180 |
1181 |
1182 |

Velocimacro Miscellany

1183 |

This section is a mini-FAQ on topics relating to Velocimacros. This section will change over time, so it's worth checking for new information from time to time.

1184 |

Note : Throughout this section, 'Velocimacro' will commonly be abbreviated as 'VM'.

Can I use a directive or another VM as an argument to a VM? 1185 |

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

1186 |

No. A directive isn't a valid argument to a directive, and for most practical purposes, a VM is a directive.

1187 |

However..., there are things you can do. One easy solution is to take advantage of the fact that 'doublequote' (") renders its contents. So you could do something like

1188 |
1189 |
1190 | #set($stuff = "#bold('hello')" )
1191 | #center( $stuff )
1192 | 
1193 |
1194 |

You can save a step...

1195 |
1196 |
1197 | #center( "#bold( 'hello' )" )
1198 | 
1199 |
1200 |

Please note that in the latter example the arg is evaluated inside the VM, not at the calling level. In other words, the argument to the VM is passed in in its entirety and evaluated within the VM it was passed into. This allows you to do things like :

1201 |
1202 |
1203 | #macro( inner $foo )
1204 |   inner : $foo
1205 | #end
1206 | #macro( outer $foo )
1207 |    #set($bar = "outerlala")
1208 |    outer : $foo
1209 | #end
1210 | #set($bar = 'calltimelala')
1211 | #outer( "#inner($bar)" )
1212 | 
1213 |
1214 |

Where the output is

1215 |
1216 |
1217 | Outer : inner : outerlala
1218 | 
1219 |
1220 |

because the evaluation of the "#inner($bar)" happens inside #outer(), so the $bar value set inside #outer() is the one that's used.

1221 |

This is an intentional and jealously guarded feature - args are passed 'by name' into VMs, so you can hand VMs things like stateful references such as

1222 |
1223 |
1224 | #macro( foo $color )
1225 |   <tr bgcolor=$color><td>Hi</td></tr>
1226 |   <tr bgcolor=$color><td>There</td></tr>
1227 | #end
1228 | #foo( $bar.rowColor() )
1229 | 
1230 |
1231 |

And have rowColor() called repeatedly, rather than just once. To avoid that, invoke the method outside of the VM, and pass the value into the VM.

1232 |
1233 |
1234 | #set($color = $bar.rowColor())
1235 | #foo( $color )
1236 | 
1237 |
Can I register Velocimacros via #parse() ? 1238 |

Currently, Velocimacros must be defined before they are first used in a template. This means that your #macro() declarations should come before using the Velocimacros.

1239 |

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. To get around this, simply use the velocimacro.library facility to have Velocity load your VMs at startup.

What is Velocimacro Autoreloading? 1240 |

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

1241 |

velocimacro.library.autoreload

1242 |

which defaults to false. When set to true along with

1243 |

<type>.resource.loader.cache = false

1244 |

(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, so you do not have to dump the servlet engine (or application) or do other tricks to have your Velocimacros reloaded.

1245 |

Here is what a simple set of configuration properties would look like.

1246 |
1247 |
1248 |     file.resource.loader.path = templates
1249 |     file.resource.loader.cache = false
1250 |     velocimacro.library.autoreload = true
1251 | 
1252 |
1253 |

Don't keep this on in production.

1254 |
1255 |
1256 |

String Concatenation

1257 |

A common question that developers ask is How do I do String concatenation? Is there any analogue to the '+' operator in Java?.

1258 |

To do concatenation of references in VTL, you just have to 'put them together'. The context of where you want to put them together does matter, so we will illustrate with some examples.

1259 |

In the regular 'schmoo' of a template (when you are mixing it in with regular content) :

1260 |
1261 |
1262 |        #set( $size = "Big" )
1263 |        #set( $name = "Ben" )
1264 |       The clock is $size$name.
1265 | 
1266 |
1267 |

and the output will render as 'The clock is BigBen'. For more interesting cases, such as when you want to concatenate strings to pass to a method, or to set a new reference, just do

1268 |
1269 |
1270 |       #set( $size = "Big" )
1271 |       #set( $name = "Ben" )
1272 |       #set($clock = "$size$name" )
1273 |       The clock is $clock.
1274 | 
1275 |
1276 |

Which will result in the same output. As a final example, when you want to mix in 'static' strings with your references, you may need to use 'formal references' :

1277 |
1278 |
1279 |       #set( $size = "Big" )
1280 |       #set( $name = "Ben" )
1281 |       #set($clock = "${size}Tall$name" )
1282 |       The clock is $clock.
1283 | 
1284 |
1285 |

Now the output is 'The clock is BigTallBen'. The formal notation is needed so the parser knows you mean to use the reference '$size' versus '$sizeTall' which it would if the '{}' weren't there.

1286 |
1287 |
1288 |
1289 |

Feedback

1290 |

If you encounter any mistakes in this manual or have other feedback related to the Velocity User Guide, please email the Velocity developers list. Thanks!

1291 |
1292 |
1293 |
1294 |
1295 |
1296 |
1297 | 1315 | 1316 | 1317 | --------------------------------------------------------------------------------