在 Java 中使用 Velocity 模板引擎,需要先引入 Velocity 相关的依赖。常见的依赖有 velocity 和 velocity-tools。
注意: Velocity 模板引擎不支持中文变量名
- 在 Maven 中,可以这样引入依赖:
<dependencies>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
- 然后可以使用以下代码来运行 Velocity 模板引擎:
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
public class VelocityExample {
public static void main(String[] args) {
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "/path/to/templates");
// 设置严格模式, 如:$!{apple}, 若apple变量不存在则报错
// velocityEngine.setProperty("runtime.references.strict", "true");
velocityEngine.init();
Template template = velocityEngine.getTemplate("hello.vm");
VelocityContext context = new VelocityContext();
context.put("name", "John Doe");
context.put("age", 25);
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}
}
在上面的示例中,我们首先创建了一个VelocityEngine实例,并设置了模板文件的路径。然后,我们加载了名为hello.vm的模板,并向其传递了“name”和“age”变量。最后,我们将合并后的模板写入StringWriter,并将其打印出来。
这就是使用Velocity模板引擎的基本步骤。您可以根据需要对模板进行更多的定制和复杂的操作。有关更多信息和示例,请参考Velocity官方文档。
- 也可以简单地使用字符串作为模板
public static void main(String[] args) {
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.init();
String templateStr = "hello, $name";
VelocityContext context = new VelocityContext();
context.put("name", "John Doe");
context.put("age", 25);
StringWriter writer = new StringWriter();
velocityEngine.evaluate(context, writer, "logTag", templateStr);
System.out.println(writer.toString());
}
-
velocityEngine.setProperty()
可设置的内容均可在org.apache.velocity.runtime.RuntimeConstants
类中查看
网友评论