nVelocity模板引擎探寻
1.下载地址:http://www.castleproject.org/castle/download.html
下载 CastleProject-1.0-RC3.msi
http://nchc.dl.sourceforge.net/project/castleproject/Castle%20Project/Release%20Candidate%203/CastleProject-1.0-RC3.msi
2.使用说明英文:http://www.castleproject.org/others/nvelocity/usingit.html
3.例子下载:下载 http://www.ajaxcn.net/file/testNVelocity.rar
using it大致有四步:
在安装目录 盘符:\Program Files\CastleProject\Bin\net-2.0下找到NVelocity.dll引用到项目
然后引入以下名称空间:
using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
第一步:Creating a VelocityEngine也就是创建一个VelocityEngine的实例
VelocityEngine velocity = new VelocityEngine(); //也可以使用带参构造函数直接实例。
ExtendedProperties props = new ExtendedProperties();
velocity.Init(props);
第二步:Creating the Template加载模板文件
这时通过的是Template类,并使用VelocityEngine的GetTemplate方法加载模板
Template template = velocity.GetTemplate(@"path/to/myfirsttemplate.vm");
第三步:Merging the template整合模板
VelocityContext context = new VelocityContext();
context.Put("from", "somewhere");
context.Put("to", "someone");
context.Put("subject", "Welcome to NVelocity");
context.Put("customer", new Customer("John Doe") );
第四步:创建一个IO流来输出模板内容。推荐使用StringWriter(因为template中以string形式存放)
StringWriter writer = new StringWriter();
template.Merge(context, writer);
Response.Write(writer.ToString());
运行问题描述
按官方操作错误Unable to find resource 'myfirsttemplate.html'
解决办法http://hi.baidu.com/dikongpulu/blog/item/8db9b745c31cf93786947332.html
具体解决办法:
在engine.Init(props);之前使用
props.AddProperty("file.resource.loader.path", Server.MapPath("."));
第2个参数Server.MapPath(".")指当前模板文件所在的目录,如果你的模板文件完整路径是:c:\xx\xx.vm
则应该把Server.MapPath(".")替换成c:\xx
本文参考了
NVelocity模板引擎初学总结:http://www.cnblogs.com/McJeremy/archive/2008/06/25/1229848.html
解决NVelocity加载模板时出现Unable to find resource"xxx"错误http://hi.baidu.com/dikongpulu/blog/item/8db9b745c31cf93786947332.html
原创文章转载请注明出处:云飞扬IT的blog





