Apache Velocity 是一种基于 Java 的模板引擎,用于在模板中动态生成文本。在 Velocity 中,占位符插值是一种常见的用法,用于将变量的值插入到模板中的特定位置。
下面是一个简单的示例,展示了如何在 Velocity 中使用占位符插值:
org.apache.velocity
velocity-engine-core
2.3.0
template.vm
,其中包含占位符 ${name}
:Hello ${name}!
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import java.io.StringWriter;
public class VelocityExample {
public static void main(String[] args) {
// 创建 Velocity 引擎
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.init();
// 创建 Velocity 上下文
VelocityContext context = new VelocityContext();
context.put("name", "world");
// 加载模板文件
Template template = velocityEngine.getTemplate("template.vm");
// 渲染模板
StringWriter writer = new StringWriter();
template.merge(context, writer);
// 输出渲染结果
System.out.println(writer.toString());
}
}
Hello world!
这个示例演示了如何使用 Apache Velocity 进行占位符插值。通过设置 Velocity 上下文中的变量值,然后将上下文与模板进行合并,可以将变量的值插入到模板中的占位符位置。