`
george.gu
  • 浏览: 70977 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Velocity Usage

阅读更多

 

You can find velocity mannual from http://velocity.apache.org/engine/devel/user-guide.html.

Here is summarize on how to use velocity.

Velocity Usage:

Velocity is a Java-based template engine. 

We can use velocity to define web page instead of JSP, there are several advantages:

 

  1. 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. 
  2. Simplify web page logical and make it more easy to be managed by web-designer
  3. Web page written in velocity template can be updated without re-deploy you web application.

 

We can also use velocity to generate other output based on template:

 

  1. XML
  2. SQL
  3. Some other file template with dynamic data by defining them in velocity syntax.

 

Variable Definition:

 

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:

 

  • alphabetic (a .. z, A .. Z)
  • numeric (0 .. 9)
  • hyphen ("-")
  • underscore ("_")

Following definition have different meaning:

$count:

Usage: #set($count=10)

define a variable named "count"

$count-1:

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.

$count -1:

Usage: #set($count=$count -1)

Error!

Exception : org.apache.velocity.exception.ParseErrorException: Encountered "-1" at...

$count - 1:

Usage: #set($count=$count - 1)

execute an evaluation which get result of $count minus 1.

has same value as "$count + -1"

${count}-1:

Usage: #set($count=${count}-1)

Error!

Get the same error as "$count -1". 

${count}- 1:

Usage: #set($count=${count}- 1)

execute an evaluation which get result of $count minus 1.

has same value as "${count}+ -1"

 

Exception

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";

]]#


 

Quiet Reference Notation "!" and conditional logical NOT "!"

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: 

 

  1. $email is a boolean (true/false) which has a true value, or 
  2. $email is NOT a boolean and its value is not null.

#include() vs. #parse():

  1. include() can contain a set of files separated by commas, like: include("file1.vm", "file2.vm", ...) But parse() can only contain one file.
  2. Velocity does not render variables inside included files, but the variables inside parse file will be rendered.
  3. You can use variable to replace filename in both.

Properties reference to Variable

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).  
So please make sure your template refer to JavaBean valid getter/setter method.
JavaBean.java as following:

  public class JavaBean {

private String a;
private String b = "Iamb";
public JavaBean() {
}
public String geta() {
return "Iama";
}
public String getA() {
return "IamA";
}
}
Your template test.vm as following:

  $bean.a

$bean.A
$bean.b
Then you set VelocityContext as following:

  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);

You will get the output as following:
Iama
IamA
$bean.b

Normally the property lookup rules as following:
  1. geta()
  2. getA()
  3. get("a")
  4. isA()

Directive:

#set:

We can set a variable in velocity with #set directive:
#set($count=10)

literal:

string literals that are enclosed in double quote characters will be parsed and rendered. 
However, when the string literal is enclosed in single quote characters, it will not be parsed

Condition: 

#if(condition1)
...
#elseif(condition2)
...
#else
...
#end 

Loops:

#foreach ($each in $all)
...
#end
you can use #break to stop looping.

velocity.properties:

I would like to discuss velocity.properties and how it control default velocity render behavior.
To be updated later.

 

分享到:
评论

相关推荐

    mat-velocity:提供velocity模板的渲染功能

    Usage var mat = require('mat') var velocity = require('mat-velocity') var rewrite = require('mat-rewrite') mat.task('daily', function () { mat.url([/\.vm/]) .use(velocity({ })) }) api 用来处理vm的...

    node-soft-mirror:使用节点的 Velocity 软镜像以毫秒为单位启动

    ##Usage 在你的框架 package.js 中引用这个包,然后在服务器上使用类似的东西: Meteor . call ( 'velocity/mirrors/request' , { framework : 'myFramework' } ) ; VelocityMirrors . find ( { framework : '...

    amazing:Velocity 前端工程问题集成解决方案

    amazing: Velocity 前端工程问题集成解决方案 Usage 全局安装amazing npm install -g amazing 到web工程的根目录下 cd /(webapp) 初始化本地服务器web工程加载目录 amazing -i 启动服务器 amazing Others 自定义端口...

    Android代码-IntelliJDashPlugin

    A smart and simple plugin that provides keyboard shortcut access for Dash, Velocity or Zeal in IntelliJ IDEA, RubyMine, WebStorm, PhpStorm, PyCharm, DataGrip, CLion, GoLand and Android Studio. ...

    GPS原理与应用英文版

    Since the writing of the first edition of this book, usage of the Global Positioning System (GPS) has become nearly ubiquitous. GPS provides the position, velocity, and timing information that enables...

    NovodeX Physics SDK Documentation

    While this documentation will cover the features and usage of the SDK, because of the academically challenging nature of the subject matter, it is assumed that you have mastered the material covered ...

    patcher:修补 Meteor 方法并允许您出于测试目的覆盖“this”属性

    您的支持帮助我们继续我们在 Velocity 和相关框架方面的工作。 #安装 meteor add xolvio:patcher#Usage 这个包设置了debugOnly标志,这意味着它不会被捆绑到应用程序中。 这也意味着您只能将其作为弱依赖引用,...

    Infinite-Alphabet Prefix Codes Optimal for Beta-Exponential Penalties (10.1.1.560.4484)-计算机科学

    Electronics for Imaging303 Velocity Way Foster City, California 94404 USAEmail: Michael.Baer@efi.comAbstract— Let P = {p(i)} be a measure of strictly positive probabilities on the set of nonnegative ...

    restful restful所需要的jar包

    * Servlet adapter provided to let you deploy any Restlet application in Servlet compliant containers like Tomcat, when the usage of standalone HTTP connectors is not possible. * Implementation of ...

    二级减速器课程设计说明书reducer design specification.doc

    (e) usage period: 10 years, minor overhaul period: 1 year, and overhaul period: 3 years; (f) power source is alternating three-phase voltage; (g) small-batch production in medium scale machinery ...

    spring chm文档

    14.4. Velocity和FreeMarker 14.4.1. 需要的资源 14.4.2. Context 配置 14.4.3. 创建模板 14.4.4. 高级配置 14.4.5. 绑定支持和表单处理 14.5. XSLT 14.5.1. 写在段首 14.5.2. 小结 14.6. 文档视图(PDF/...

    Spring中文帮助文档

    14.4. Velocity和FreeMarker 14.4.1. 需要的资源 14.4.2. Context 配置 14.4.3. 创建模板 14.4.4. 高级配置 14.4.5. 绑定支持和表单处理 14.5. XSLT 14.5.1. 写在段首 14.5.2. 小结 14.6. 文档视图(PDF/...

    Spring API

    14.4. Velocity和FreeMarker 14.4.1. 需要的资源 14.4.2. Context 配置 14.4.3. 创建模板 14.4.4. 高级配置 14.4.5. 绑定支持和表单处理 14.5. XSLT 14.5.1. 写在段首 14.5.2. 小结 14.6. 文档视图(PDF/...

Global site tag (gtag.js) - Google Analytics