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更改为
${welcome} ${user.name}
You are an ${user.type}
所以输出将是一个html页面,没有java代码中的单一更改.
因此,像Velocity这样的模板引擎(例如Thymeleaf或Freemarker)的使用让设计师能够完成设计师的工作,程序员可以完成程序员的工作,同时对彼此的干扰最小.