什么是Apache Velocity? [英] What is Apache Velocity?
问题描述
有人可以解释一下,什么是Apache Velocity? 它的目的是什么?
Can someone please explain, what is Apache Velocity ? what is its purpose ?
提供一个示例很好.
谢谢.
推荐答案
Apache Velocity is a template engine. That means that you can add variables to a context, load a template in which those variables are referenced and render a text from this template where the references to the variables are replaced with the variable's actual value.
其目的是将设计和静态内容与代码分开.以一个网站为例.您不想在Java代码中创建HTML,是吗?每次更改一些设计时,您都必须重新编译您的应用程序,并且会因不必要的设计混乱而污染您的代码.您宁愿想获取变量,无论是计算得出的变量,还是从数据库获得的变量,都可以让设计者创建一个HTML模板,在其中使用变量.
It's purpose is to separate design and static content from code. Take a website for example. You don't want to create HTML inside your java code, do you? You would have to recompile your app every time you change a bit of design and you would polute your code with unnecessary design clutter. You would rather want to get your variables, either computed or from a database or whatever and have a designer create a HTML template in which your variables are used.
一些伪代码可以使之清晰明了:
Some pseudo code to make it clear:
/* 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 VelocityContext();
/* 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的文件
Now given a file called myTemplate.vm
${welcome} ${user.name}!
You are an ${user.type}.
输出为:
Hello, Foo!
You are an admin.
现在,让我们假设纯文本应为HTML.设计人员会将myTemplate.vm更改为
Now let's assume the flat text should be HTML instead. The designer would change myTemplate.vm to
<html>
<body>
<h1>${welcome} ${user.name}</h1>
<p>You are an ${user.type}</p>
</body>
</html>
因此输出将是html页面,而在Java代码中没有任何更改.
So the output would be a html page without a single change in the java code.
因此,使用了诸如Velocity之类的模板引擎(还有其他模板引擎,例如Thymeleaf 或Freemarker )可让设计人员完成设计人员的工作,而程序员则在对程序员造成最小干扰的情况下完成程序员的工作彼此.
So the use of a template engines like Velocity (there are others, e.g. Thymeleaf or Freemarker) let designers do a designer's job and programmers do a programmer's job with minimal interference to each other.
这篇关于什么是Apache Velocity?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!