What is Velocity?
Velocity is a Java-based template engine. It allows the web page developer to reference the method defined in the Java code. Web designers can develop a WEB site that follows the MVC mode with the Java program developer parallel. This means that the web designer can focus on a good Web site, while Java program developers can put their energy on writing code. Velocity Separates the Java code from the web page to make the Web site longer-maintainable and provide an alternative JSP or PHP solution.
VTL (Velocity Template Language)
VTL provides a simple, easy and quiet way to merge dynamic content into the web page. VTL uses references to insert dynamic content into the web page. Variables are a reference that can point to define content in the Java code, or a VTL statement in the web page. Below is an example of a VTL statement that can be inserted into the HTML document:
#set ($ a = "velocity")
The VTL statement begins with # and contains instructions (SET). The variable is started with a quotation mark. The quotation marks can be single or double quotes. The former references the specific string value; the latter can include Velocity references, such as "Hello, $ Name", $ NAME will replace it with its current value. The above example is to assign value Velocity to the variable a.
When the variable is assigned, you can reference anywhere in the HTML document, the following is an example of Hello Velocity World!
#set ($ foo = "velocity")
Hello $ foo world!
Comment
VTL supports a single-line annotation (starting in ##) and multi-line comments (including between # * and * #), the following is an example:
This text is visible. ## THIS TEXT IS NOT Visible.
This text is visible.
This text is visible. # * This text, as part of a multi-line comment,
Is Not Visible. This Text Is Not Visible; It is Also Part of The
Multi-line Comment. this text still not visible. * # this text is outside
The comment, so it is visible.
## THIS TEXT IS Not Visible.
References
VTL has three types of reference: variables, attributes, and methods. As a designer, the Java engineer must be consistent with the name (identifier) referenced by the VTL reference to use them in the template. The reference is handled as a String object.
(1) variable
Variable format: $ VTL identifier
The VTL identifier consists of letters, numbers, transverse lines (-) or underscores (_). Variables or Values (as described above), or Java code (same name variable) from the SET instructions in the template. Velocity only processes the defined variable reference, and Velocity returns to the unfined variable reference. For example, the following example:
#set ($ foo = "gibbous")
$ moon = $ foo
The output is: $ moon = Gibbous
(2) attribute
Property Format: $ VTL Identifier. VTL Identifier
Below is an example of attribute reference:
$ Customer.Address
$ purchase.total
Take the first example, there are two interests:
l Return to the value of the HashTable object Customer key value is Address
l $ Customer.GetDress () Method Reference Abbreviation (Getter Method for Javabean Properties)
As for which case, Velocity will make decisions and return the appropriate value.
(3) method
Method's format: $ VTL identifier (parameter list)
Here is an example of method reference:
$ Customer.Getaddress ()
$ purchase.gettotal ()
$ Page.Settitle ("My Home Page")
$ Person.SetaTRibutes (["Strange", "Weird", "Excited"])
Two examples of the previous examples can abbreviate the property reference (such as an example of attribute reference). Properties references and method references are the main differences for methods to specify a list of parameters.
(4) Formal reference symbol: {}
The official reference symbols are distinguished in the use of variables. Look at the example below:
#set ($ vice = "klepto")
Jack is a $ ViceManiac.
The output is: Jack IS A $ ViceManiac. ($ ViceManiac is not defined, the output is output)
#set ($ vice = "klepto")
Jack is a $ {vice} maniac.
The output result is: Jack Is A Kleptomaniac. (Separate $ VICE and other text) using official reference symbols)
(5) Quit reference symbol:!
Look at the example below:
At the beginning, $ email doesn't have a value, so the value of $ Email will be displayed in the text box, but more hope is blank. Here is an example of using a quit reference symbol:
Velocity will replace $ EMAIL with an email when $ email is no value.
(6) Special character escape
For special characters such as $, # to be displayed normally, you can use / perform escape, // escape. Below is an example:
#set ($ email = "foo")
The output result is:
foo
/ foo
Directives
The reference allows the template designer to generate dynamic content for the web site, and instructions make the script elements that are cleverly handle the Java code.
(1) #set
Format: #set (lhs = rhs)
l LHS can be a variable reference or attribute reference
l RHS can be a reference, string, number, arraylist or map
The following example shows each RHS type above:
#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 Litral
#set ($ monkey.say = ["not", $ my, "fault"]) ## arraylist
#set ($ monkey.map = {"banana": "good", "roast beef": "Bad"}) ## map
For ArrayList and MAP, you can use the corresponding Java method to access the element values:
$ monkey.say.get (0)
$ monkey.map.get ("bannana")
$ monkey.map.banana ## Same as Above
l RHS can be a simple arithmetic expression
#set ($ VALUE = $ FOO 1) ## addition
#set ($ value = $ bar - 1) ## Subtraction
#set ($ value = $ foo * $ bar) ## Multiplication
#set ($ value = $ foo / $ bar) ## division
#set ($ VALUE = $ FOO% $ BAR) ## remainder
Math expressions are only supported. / The result is an integer; if it is not interstitial, return NULL
l If the result of RHS is null, it will not assign a value to LHS.
Look at the example below:
#set ($ criteria = ["name", "address"])
#foreach ($ criterion in $ criteria)
#set ($ Result = $ query.criteria ($ criterion))
#if ($ Result)
Query Was Successful
#end
#end
It is problematic to use $ Result to check if it is executed. If the first execution is successful, $ Result is not null, then the rear execution regards no matter whether it is successful, the inspection condition is always established. The improved approach is to initialize the FALSE before each execution:
#set ($ criteria = ["name", "address"])
#foreach ($ criterion in $ criteria)
#set ($ result = false)
#set ($ Result = $ query.criteria ($ criterion))
#if ($ Result)
Query Was Successful
#end
#end
l String text can be enclosed in double quotes or single quotes. The main difference between the two is that the reference in the dual quotes will replace the corresponding value, and the references in single quotes are exported.
#set ($ DIRECTORYROOT = "WWW")
#set ($ TemplateName = "INDEX.VM")
#set ($ Template = "$ DIRECTORYROOT / $ TEMPLATENAME")
$ Template
The output result is: www / index.vm
If you use single quotes:
#set ($ Template = '$ DIRECTORYROOT / $ TEMPLATENAME')
The output is: $ DIRECTORYROOT / $ TEMPLATENAMEL Use Double quotes to implement string series, as follows:
#set ($ size = "big")
#set ($ Name = "BEN")
#set ($ clock = "$ {size} tall $ name")
The clock is $ clock.
(2) #if / #elseif / #else
When the #IF command is established, the content between #IF and #end, otherwise the content between #ELSE and #END is displayed. Below is an example:
#if ($ foo)
Velocity!
#end
There are two cases:
l If $ foo is Boolean, $ foo is True;
l Otherwise, $ foo is not NULL
The relationships and logic symbols that can be used in the #IF instruction include:
l <, <=, ==,> =,>
L && (and), || (OR),! (not)
(3) Cycling: foreach
Below is an example:
#foreach ($ Product In $ AllProducts)
$ Product
#end
The content of $ allProducts can be a vector, havehtable or arraylist, each time a value assignment to $ Product; the returned value is a Java object, which can be used to reference the specific method. The following example assumes that $ allproducts are the HashTable object:
#foreach ($ Key in $ allproducts.keyset ())
KEY: $ Key -> Value: $ allproducts.get ($ key)
#end
Velocity provides a simple way to access loop count variables:
#foreach ($ Customer IN $ Customerlist)
#end
$ VELOCITYCOUNT $ Customer.Name
$ VelocityCount is Velocity Indicates the internal variable of the loop count, and the default start value is 1. This setting is defined in the velocity.properties file:
# Default name of the loop counter
# Variable Reference.
Directive.Foreach.counter.name = velocitycount
# Default Starting Value of The Loop
# counter variable reference.
Directive.Foreach.counter.initial.Value = 1
You can use the range operator [N "in the #foreach command, where n and m must be intellectual:
First EXAMPLE:
#foreach ($ foo in [1..5])
$ foo
#end
SECOND EXAMPLE:
#foreach ($ BAR IN [2 ..- 2])
$ bar
#end
Third Example:
#set ($ arr = [0..1])
#foreach ($ I IN $ ARR)
$ I
#end
The output result is:
First EXAMPLE:
1 2 3 4 5
SECOND EXAMPLE:
2 1 0 -1 -2
Third Example:
0 1
(4) # clude # include instructions to import local files to the #include command definition. The imported file content is not parsed by the template engine. For security reasons, the imported file should be placed in the template_root directory. You can import multiple files at a time, with a comma-separated comma; and usually use variable references to replace file names. Below is an example:
#include ("Greetings.txt", $ SeasonalStock)
(5) #parse
#parse instruction allows importing a local file containing VTL and parsed by a template engine. The #PARSE instruction imported file must be placed in the template_root directory and only one file can be imported at a time. Allows the #parse instructions in the Velocity template. The maximum depth is defined by PARSE_DIRECTIVE.MAXDEPTH in the Velocity.properties file. Below is an example:
Count down.
#set ($ count = 8)
#PARSE ("Parsefoo.VM")
All done with dofoo.vm!
The contained Parsefoo.vm file is as follows:
$ count
#set ($ count = $ count - 1)
#if ($ count> 0)
#PARSE ("Parsefoo.VM")
#ELSE
All done with parsefoo.vm!
#end
The output result is:
Count Down. 8 7 6 5 4 3 2 1 0 All Done with parsefoo.vm! All done with dofoo.vm!
(6) #Stop
#STOP instruction stops the execution of the template engine and returns. This is useful in Debug.
(7) #macro
#macro instruction allows you to define a reused VTL template (called Velocimacros).
l Velocimaos can have 0 or more parameters. Below is an example:
#macro (TableRows $ SOMELIST)
#foreach ($ Something In $ SOMELIST)
$ Something
#end
#end
This VelociMacro called TableRows has 2 parameters: a color and an array. The following code contains pairs
TABLEROWS call:
#SET ($ Greatlakes = ["Superior", "Michigan", "Huron", "Erie", "Ontario"])
#set ($ color = "blue")
#TABLEROWS ($ Color $ Greatlakes)
The output is:
Superiormichiganhuronerieontario
l Velocimacros can be defined in the VTL template, which is invalid to other VTL templates; to make VelocimaS in all VTL templates, you can define Velocimracros template (globally).
l VelocimaS properties are defined in the Velocity.properties file to provide flexibility in implementing VelocimaS:
Velocimaracro.library = vm_global_library.vm
Velocimaracro.Permissions.Allow.inline = trueVelocimracro.Permissions.Allow.inline.to.replace.global = false
Velocimracro.Permissions.Allow.inline.local.scope = false
VelocimaCro.Context.localscope = false
Velocimaracro.library.autoreLoad = false
Velocimracro.library: Defines a comma-separated VelociMacros global template library, default is VM_GLOBAL_LIBRARY.VM, you can add custom template libraries;
Velocimracro.Permissions.Allow.inline: Specifies whether VelocimaS is defined in the VTL template, default is true; allowed;
Velocimracro.Permissions.Allow.inline.to.Replace.global: Specifies whether to allow inline defined VelociMacros to replace the global VelociMacros with the same name, the default is false;
Velocimracro.Permissions.Allow.INline.local.scope: Specifies whether the Inline definition is a defined template, and the default is false;
Velochacro.Context.localscope: Specifies whether the Context content is local, the default is false; if set to true, use the #set directive to modify CONTEXT only valid in local scope and will not permanently affect the context;
Velocimracro.library.AutoreLoad: Specifies whether the VelociMacros template library is automatically loaded, the default is false; if set to true, when the VelociMacro in the Velocimros Template is called, the template library will be updated and reloaded again when needed; The premise is file.Resource.Loader.cache = false; this property should be used when developing, not the product phase;
l Velocimacros must be defined before the first use. Therefore, the #parse instruction contains the type of Velocimaos, which is inline, there is a problem, and a simple solution is to define VelociMacros to the template library so that Velocity is loaded.
l Quote When parameters as Velocimaos are used in the form of by name, this means that their value is obtained each time in VelocimaS.
l Velocimaos cannot be passed as a parameter to another Velocimaos, such as:
#Center (#bold ("Hello") ## invalid
You can use the following form to achieve the same purpose:
#Center ("#bold ('Hello')") ## Right
Below is an example of a nested call:
#macro (Inner $ FOO)
Inner: $ foo
#end
#macro (Outer $ foo)
#set ($ bar = "outerlala")
Outer: $ foo
#end
#set ($ bar = 'caltimela') # Outer ("#inner ($ bar)")
The result of the output is: Outer: Inner: Outerlala
Because the parameters are passed in by Name, set the value of $ bar in the interior of #outer, then call #inner