摘要:看了博客园中一些对NVelocity的介绍,感觉很有意思,自己实验了一次,出现了好多问题,最后才总算可以运行起来。通过网上的介绍实践下,内容如下:
一、NVelocity的介绍
这个网上一大堆,我不介绍了。
二、NVelocity的引用
using Commons.Collections; //ExtendedProperties需要
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
三、测试的类
public class Customer { private string name; public string Name { get { return name; } } public Customer(string n) { this.name = n; } }
四、NVelocity模板classes.vm
1 From: $from 2 To: $to 3 Subject: $subject 4 5 Hello $customer.Name 6 7 We're please to yada yada yada.
五、代码生成
1 private void testcod() 2 { 3 VelocityEngine ve = new VelocityEngine(); 4 ExtendedProperties props = new ExtendedProperties(); 5 ve.Init(props); 6 7 Template tl = ve.GetTemplate(@"\Template File\classes.vm"); 8 9 VelocityContext vctx = new VelocityContext(); 10 vctx.Put("from","sqlitehelper"); 11 vctx.Put("to", "someone"); 12 vctx.Put("subject", "Welcome to NVelocity"); 13 vctx.Put("customer", new Customer("测试人员") ); 14 15 StringWriter sw = new StringWriter(); 16 17 tl.Merge(vctx,sw); 18 19 richTextBox1.Text = sw.GetStringBuilder().ToString(); 20 }
Template File文件夹位于程序运行的目录下,不能为绝对路径。
六、测试结果
1 From: sqlitehelper 2 To: someone 3 Subject: Welcome to NVelocity 4 5 Hello 测试人员 6 7 We're please to yada yada yada.
结束语:感觉简单,可是在自己测的过程中找不到vm模板文件,根据百度搜索知要把vm设置为嵌套资源,我的没有设置,就是路径设置问题设置成了全路径,出现了此问题。
看来真不简单哦。
参考:http://www.castleproject.org/others/nvelocity/usingit.html