1、创建一般处理程序 ashx 文件
context.Response.ContentType = "text/html";
修改上下文类型为 html
2、创建一个全局类
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;
//以上引入 Nvelocity
namespace Demo.Web
{
public class Common : System.Web.UI.Page
{
/// <summary>
/// 创建HTML文件
/// </summary>
/// <param name="TempFrom">模板文件路径</param>
/// <param name="PhysicalPath">要生成的 html 保存位置</param>
/// <param name="TempName">生成的模板名称</param>
/// <param name="data">传给 NVelocity 的数据 DataRow</param>
public static void CreateHTML(string TempFrom,string PhysicalPath,string TempName,object data)
{
//创建NVelocity引擎的实例对象
VelocityEngine velocity = new VelocityEngine();
//初始化该实例对象
ExtendedProperties props = new ExtendedProperties();
props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Path.GetDirectoryName(PhysicalPath));
props.AddProperty(RuntimeConstants.INPUT_ENCODING, "gb2312");
props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312");
velocity.Init(props);
//从文件中读取模板
Template temp = velocity.GetTemplate(TempFrom);
IContext context = new VelocityContext();
context.Put("Data", data);
//合并模板
StringWriter writer = new StringWriter();
//velocity.MergeTemplate(context, writer);
temp.Merge(context, writer);
//生成静态页
using (StreamWriter writer2 = new StreamWriter(PhysicalPath + TempName, false, Encoding.UTF8, 200))
{
writer2.Write(writer);
writer2.Flush();
writer2.Close();
}
}
}
}