volocity加载模板&输出

本文详细介绍了如何在Volocity软件中加载模板以及如何实现动态模板输出,包括步骤指导和常见问题解决,帮助用户更好地理解和应用Volocity工具。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、通过绝对路径加载vm模板
//初始化模板引擎
VelocityEngine ve = new VelocityEngine();

ve.init();

//根据绝对路径获取模板
Template template = ve.getTemplate("d:/test.vm"); 

//velocity上下文context
VelocityContext context = new VelocityContext();

//设置变量
context.put("name", "test");

//输出流
StringWriter writer = new StringWriter();

//转换输出
template.merge(context, writer);

System.out.println(writer.toString());

2、加载包路径下的vm模板
//模板引擎
VelocityEngine ve = new VelocityEngine();

Properties props = new Properties();        
props.setProperty("resource.loader", "class");
props.setProperty("class.resource.loader.class",
		"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

ve.init(props);

//获取包路径com.cd下的test1.vm模板		
Template template = ve.getTemplate("com/cd/test1.vm");

//velocity上下文context
VelocityContext context = new VelocityContext();

//设置变量
context.put("name", "test");

//输出流
Writer out = new OutputStreamWriter(new FileOutputStream(
					new File("d:/test.doc")),"UTF-8");
					
template.merge(context, out);
            
template.process();

3、加载动态字符串形式模板
//Velocity引擎
VelocityEngine ve = new VelocityEngine();

ve.init();

//模板
String content = "hello $name";

//velocity上下文context
VelocityContext context = new VelocityContext();

//设置变量
context.put("name", "world.");

// 输出流
StringWriter writer = new StringWriter();

// 转换输出
ve.evaluate(context, writer, "", content); 

System.out.println(writer.toString());


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值