我们扩展Page类创建一个PageAdapter.cs (用于添加模板支持)

C# Code
[http://www.xueit.com]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
namespace Rsion.Web
{
/// <summary>
/// WebPage页面辅助适配器类
/// </summary>
public class PageAdapter
{
private Page page;
public PageAdapter(Page page)
{
this.page = page;
}
/// <summary>
/// 显示模板
/// </summary>
/// <param name="partialPath">模板文件路径:不带后缀[模板后缀.tpl]如/bottom将显示Templates下的bottom.tpl文件</param>
public void RenderPartial(string partialPath)
{
string templateID="Template_" partialPath.Replace("/", "_");
object o = HttpRuntime.Cache[templateID];
if (o == null)
{
FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath("~/templates/" partialPath ".tpl"));
if (!fi.Exists) return;
string templateContent;
using (StreamReader sr = new StreamReader(fi.FullName))
{
templateContent = sr.ReadToEnd();
}
//转换
TransformTemplateTags(ref templateContent);
//写入缓冲
HttpRuntime.Cache.Insert(templateID, templateContent, null,
DateTime.Now.AddMinutes(Application.TemplateCacheTime),TimeSpan.Zero);
HttpContext.Current.Response.Write(templateContent);
}
else
HttpContext.Current.Response.Write(o.ToString());
}
/// <summary>
/// 转换模板内容
/// </summary>
/// <param name="templateContent"></param>
private void TransformTemplateTags(ref string templateContent)
{
string templateID;
string pattern=@"${(w )}";
Regex rg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
foreach(Match m in rg.Matches(templateContent))
{
templateID = Regex.Replace(m.Captures[0].Value, pattern, "$1");
templateContent = Regex.Replace(templateContent, @"${" templateID "}",
Application.Template.Rules[templateID].ToString());
}
}
/// <summary>
/// 转换该页的标签内容
/// </summary>
public void TransformPageTags()
{
///
///TO:DO..
///
}
}
}
精彩图集