// 引入 Velocity 包
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
public class VelocityExample {
public static void main(String[] args) {
// 初始化 Velocity 引擎
Velocity.init();
// 创建上下文对象,用于存储模板数据
VelocityContext context = new VelocityContext();
context.put("name", "World");
// 加载模板文件
Template template = Velocity.getTemplate("hello.vm");
// 将上下文数据和模板合并输出
StringWriter writer = new StringWriter();
template.merge(context, writer);
// 输出结果
System.out.println(writer.toString());
}
}
org.apache.velocity
相关的包。Velocity.init()
方法来初始化 Velocity 引擎。VelocityContext
对象来存储模板中需要使用的变量和数据。Velocity.getTemplate()
方法加载 .vm
文件(Velocity 模板文件)。template.merge()
方法将上下文中的数据与模板进行合并,并将结果写入到 StringWriter
中。确保你有一个名为 hello.vm
的模板文件,内容如下:
Hello $name!
这样运行代码后,会输出 Hello World!
。
上一篇:java 文件读取
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站