You can find velocity mannual from http://velocity.apache.org/engine/devel/user-guide.html.
Here is summarize on how to use velocity.
Velocity is a Java-based template engine.
We can use velocity to define web page instead of JSP, there are several advantages:
We can also use velocity to generate other output based on template:
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:
Usage: #set($count=10)
define a variable named "count"
Usage: #set($count-1=10)
define a variable named "count-1". Warning: it is not a evaluation to get the value of $count minus 1.
Usage: #set($count=$count -1)
Error!
Exception : org.apache.velocity.exception.ParseErrorException: Encountered "-1" at...
Usage: #set($count=$count - 1)
execute an evaluation which get result of $count minus 1.
has same value as "$count + -1"
Usage: #set($count=${count}-1)
Error!
Get the same error as "$count -1".
Usage: #set($count=${count}- 1)
execute an evaluation which get result of $count minus 1.
has same value as "${count}+ -1"
But if you want to display "10-1" in your output, you can use following template:
#set( $count=10)
${count}-1
#[[
$count-1 will lead to "$count-1", because there is no variable named "count-1";
$count -1 will lead to "10 -1" which has one more space than "10-1".
$!count-1 will lead to " ", because there is no variable named "count-1";
]]#
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.
my email is "$email"
In case there is no variable defined for $email, it will display: my email is "$email".
If you set Quiet Reference Notation as following:
my email is "$!email"
In case there is no variable defined for $email, it will display: my email is "".
But conditional logical NOT is different:
#if(!$email)
I have no email.
#else
my email is "#email"
#end
Note: if only one variable is evaluated to determine whether it is true, like if($email). Which will happen under one of two circumstances:
public class JavaBean {
private String a;
private String b = "Iamb";
public JavaBean() {
}
public String geta() {
return "Iama";
}
public String getA() {
return "IamA";
}
}
|
$bean.a
$bean.A
$bean.b
|
VelocityContext context = new VelocityContext();
context.put("bean", new JavaBean());
PrintWriter writer = new PrintWriter(System.out);
Template template = Velocity.getTemplate("test.vm");
template.merge(context, writer);
|