Nvelocity 模板引擎 实例
看了小泥鳅博客源码,觉得模板引擎是个好东西,参考了源代码写了基于Nvelocity模板引擎的实例。写着玩的,欢迎拍砖。 项目结构如下:
关键代码:TemplateHelper.cs Nvelocity辅助类,参考NVelocity 操作类VelocityHelper
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
using Commons.Collections;
using System.IO;
using NVelocity.Runtime;
namespace NVelocityApp.Core
{
public class TemplateHelper
{
private VelocityEngine velocity = null;
private IContext context = null;
private string templatFileName;
public TemplateHelper(string templatePath)
{
velocity = new VelocityEngine();
//使用设置初始化VelocityEngine
ExtendedProperties props = new ExtendedProperties();
props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath);
props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
// props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312");
// props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
// props.SetProperty(RuntimeConstants.RESOURCE_MANAGER_CLASS, "NVelocity.Runtime.Resource.ResourceManagerImpl\\,NVelocity");
velocity.Init(props);
//RuntimeConstants.RESOURCE_MANAGER_CLASS
//为模板变量赋值
context = new VelocityContext();
}
/// <summary>
/// 给模板变量赋值
/// </summary>
/// <param name="key">模板变量</param>
/// <param name="value">模板变量值</param>
public void Put(string key, object value)
{
//if (context == null)
// context = new VelocityContext();
context.Put(key, value);
}
/// <summary>
/// 生成字符
/// </summary>
/// <param name="templatFileName">模板文件名</param>
public string BuildString(string templateFile)
{
//从文件中读取模板
Template template = velocity.GetTemplate(templateFile);
//合并模板
StringWriter writer = new StringWriter();
template.Merge(context, writer);
return writer.ToString();
}
/// <summary>
/// 显示模板
/// </summary>
/// <param name="templatFileName">模板文件名</param>
public void Display(string templatFileName)
{
//从文件中读取模板
Template template = velocity.GetTemplate(templatFileName);
//合并模板
StringWriter writer = new StringWriter();
template.Merge(context, writer);
//输出
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(writer.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace NVelocityApp.Core
{
public class TagFields
{
/// <summary>
/// 网站名称
/// </summary>
public const string SITE_NAME = "sitename";
/// <summary>
/// 网站描述
/// </summary>
public const string SITE_DESCRIPTION = "sitedescription";
/// <summary>
/// 文章列表
/// </summary>
public const string Article_LIST = "articlelist";
}
}
PageMethod.cs 页面处理类,主要向相应模板传递数据。有点像MVC中的C。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace NVelocityApp.Core
{
public class PageMethod
{
public void index(TemplateHelper th)
{
string aa = HttpContext.Current.Request.QueryString["t"];
th.Put(TagFields.SITE_NAME, "测试网站");
}
public void list(TemplateHelper th)
{
List<Person> list = new List<Person>();
for (int i = 0; i <= 5; i++)
{
list.Add(new Person { ID = i.ToString(), Name = "第" + i + "个用户" });
}
th.Put(TagFields.SITE_NAME, "测试网站");
th.Put(TagFields.Article_LIST, list);
}
}
}
Entity 下的是实体。当做测试用。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NVelocityApp.Core
{
public class Person
{
public string ID
{
get;
set;
}
public string Name
{
get;
set;
}
}
}
没有写业务层与数据层,可以根据情况扩展。
Default.aspx.cs 中代码,通过反射调用PageMethod.cs中方法。反射的用法可以参考。反射学习笔记(1)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NVelocityApp.Core;
using System.Reflection;
namespace NVelocityApp
{
public partial class _Default : System.Web.UI.Page
{
/// <summary>
/// 模板封装类
/// </summary>
private TemplateHelper th = null;// new TemplateHelper();
/// <summary>
/// 模板路径
/// </summary>
private string templatePath = null;
protected void Page_Load(object sender, EventArgs e)
{
string cmd = Request.QueryString["t"];//页面唯一限定名
//可以设置读取
templatePath = Server.MapPath(string.Format("/themes/{0}/template/", "default"));
th = new TemplateHelper(templatePath);
try
{
Assembly ass = Assembly.Load("NVelocityApp.Core");
object obj = ass.CreateInstance("NVelocityApp.Core.PageMethod");
var method = obj.GetType().GetMethod(cmd);
if (method != null)
{
method.Invoke(obj, new object[] { th });
th.Display(cmd + ".html");
}
}
catch (Exception)
{
}
}
}
}
Intelligencia.UrlRewriter.dll URL重写组件。也可以自己写个httpModules或HttpHandel处理,我直接用开源组件了,方便嘛。如果不熟悉的朋友可以参考。Url 重写
rewrite.xml 重写规则
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version="1.0" encoding="utf-8" ?>
<rewriteRules>
<rewrite url="~/Default.aspx" to="~/Default.aspx?t=index" processing="stop" />
<rewrite url="~/Index" to="~/Default.aspx?t=index" processing="stop" />
<rewrite url="~/List" to="~/Default.aspx?t=list" processing="stop" />
</rewriteRules>
当然还有最重要的Nvelocity语法,可以看看这个nVelocity使用简介。
源码在这:NVelocityApp.rar