使用NVelocity[翻译]
原文参见:http://www.castleproject.org/others/nvelocity/usingit.html
有的地方并不是全文对照翻译,只是意译
这是一个非常基本的NVelocity的使用说明。NVelocity可以把模板和数据动态合并 (不光是MonoRail的web页面可以使用,其他诸如发送邮件等也可以使用)
为了演示简单,下面的例子我们使用一个邮件的模板
第一步:生成VelocityEngine
开始必须有一个engine的实例。初始化实例的时候可以包含一些属性来指定NVelocity的编码、cache等
using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;




VelocityEngine velocity = new VelocityEngine();

ExtendedProperties props = new ExtendedProperties();
velocity.Init(props);
第二步:生成模板
假设我们生成一个邮件模板,如下所示:
From: $from
To: $to
Subject: $subject

Hello $customer.Name

We're please to yada yada yada.
用文件的绝对路径(相对路径也是可以的)使用下面一行c#代码:
Template template = velocity.GetTemplate(@"path/to/myfirsttemplate.vm");
第三步:合并模板
主要是将数据和模板合并生成最后的内容。可以在模板中使用context
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") );
最后使用writer,比如StringWriter输出内容,代码如下所示:
StringWriter writer = new StringWriter();
template.Merge(context, writer);
Console.WriteLine(writer.GetStringBuilder().ToString());
有的地方并不是全文对照翻译,只是意译
这是一个非常基本的NVelocity的使用说明。NVelocity可以把模板和数据动态合并 (不光是MonoRail的web页面可以使用,其他诸如发送邮件等也可以使用)
为了演示简单,下面的例子我们使用一个邮件的模板
第一步:生成VelocityEngine
开始必须有一个engine的实例。初始化实例的时候可以包含一些属性来指定NVelocity的编码、cache等












第二步:生成模板
假设我们生成一个邮件模板,如下所示:








第三步:合并模板
主要是将数据和模板合并生成最后的内容。可以在模板中使用context





最后使用writer,比如StringWriter输出内容,代码如下所示:



使用以上代码之后就可以在控制台中看到合并后的结果