net模板引擎 NVelocity
1、来自百度百科的介绍
nVelocity是一个基于.NET的模板引擎(template engine)。它允许任何人仅仅简单的使用模板语言(template language)来引用由.NET代码定义的对象。
当nVelocity 应用于web开发时,界面设计人员可以和.NET程序开发人员同步开发一个遵循MVC架构的web站点,也就是说,页面设计人员可以只关注页面的显示效果,而由.NET程序开发人员关注业务逻辑编码。nVelocity将.NET代码从web页面中分离出来,这样为web站点的长期维护提供了便利,同时也为我们在aspx之外又提供了一种可选的方案。
nVelocity的能力远不止web站点开发这个领域,例如,它可以从模板(template)产生SQL和PostScript、XML,它也可以被当作一个独立工具来产生源代码和报告,或者作为其他系统的集成组件使用。nVelocity也可以为很多web开发架构提供模板服务(template service)。我们的系统就提供一个模板服务的方式允许一个web应用以一个真正的MVC模型进行开发。
2、使用方法
(1)新建NVelocityEngine: VelocityEngine velocity = new VelocityEngine();
(2)配置 NVelocityEngine:
ExtendedProperties props = new ExtendedProperties();
props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateFolder);//TemplateFolder为模板文件夹路径
props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
velocity.Init(props);
(3)输出模板字符串
string result = String.Empty;
Template template = velocity.GetTemplate(fileName); //file为模板名称
if (template != null)
{
using (StringWriter sw = new StringWriter())
{
IContext ctx = new VelocityContext();
template.Merge(ctx, sw);
sw.Flush();
result = sw.ToString();
sw.Close();
}
}
return result;

浙公网安备 33010602011771号