什么是Apache Velocity?

时间:2014-04-24 05:52:31

标签: java apache velocity

有人可以解释一下,什么是Apache Velocity? 它的目的是什么?

随着它提供一个例子会很好。

提前致谢。

1 个答案:

答案 0 :(得分:24)

Apache Velocity是template engine。这意味着您可以向上下文添加变量,加载引用这些变量的模板,并从此模板中呈现文本,其中变量的引用将替换为变量的实际值。

它的目的是将设计和静态内容与代码分开。以一个网站为例。你不想在你的java代码中创建HTML,对吗?每次更改设计时都必须重新编译应用程序,并且会使用不必要的设计混乱来修改代码。您宁愿想要获取变量,无论是计算的还是来自数据库或其他任何变量,并让设计人员创建一个使用变量的HTML模板。

一些伪代码可以说清楚:

/* The user's name is "Foo" and he is of type "admin"*/
User user = getUserFromDatabase("Foo");

/* You would not add hard coded content in real world.
 * it is just to show how template engines work */
String message = "Hello,";

Velocity.init(); /* Initialises the Velocity engine */

VelocityContext ctx = new VerlocityContext();

/* the user object will be available under the name "user" in the template*/
ctx.put("user",user); 
/* message as "welcome" */
ctx.put("welcome",message);

StringWriter writer = new StringWriter();

Velocity.mergeTemplate("myTemplate.vm", ctx, writer);

System.out.println(writer);

现在给出一个名为myTemplate.vm的文件

${welcome} ${user.name}!
You are an ${user.type}.

输出结果为:

Hello, Foo!
You are an admin.

现在让我们假设平面文本应该是HTML。设计者会将myTemplate.vm更改为

<html>
<body>
  <h1>${welcome} ${user.name}</h1>
  <p>You are an ${user.type}</p>
</body>
</html>

因此输出将是一个html页面,而不是 java代码中的单个更改。

因此使用像Velocity这样的模板引擎(还有其他模板引擎,例如ThymeleafFreemarker)可以让设计师完成设计师的工作,程序员可以完成程序员的工作,对彼此的干扰最小。 / p>