.net c# 一個簡單但是功能強大動態模板引擎(一) 收藏
注意:歡迎轉載,但是請註明出處.
流行的模板引擎有很多,譬如velocity.但是他的範本語言比較簡,複雜的功能比較難實現,而且編輯模板比較麻煩容易出錯.
但是利用UserControl就可以實現功能強大的一個動態模板引擎,編輯的模板的時候跟編輯一個使用者控制項沒有區別,並且支援任何.net語言譬如c#.
下面就是代碼:
view plaincopy to clipboardprint?
using System;
using System.Collections.Generic;
using System.Text;
namespace Template
{
public class TemplateBody : System.Web.UI.UserControl
{
private IDictionary<string, object> _context = new Dictionary<string, object>();
protected void Page_Load(object sender, EventArgs e)
{
}
public IDictionary<string, object> ViewData
{
get { return _context; }
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Template
{
public class TemplateBody : System.Web.UI.UserControl
{
private IDictionary<string, object> _context = new Dictionary<string, object>();
protected void Page_Load(object sender, EventArgs e)
{
}
public IDictionary<string, object> ViewData
{
get { return _context; }
}
}
}
TemplateBody類基本沒什麼代碼只是聲明了一個ViewData屬性,該屬性用於向模板添加資料由模板來擷取並展示.
view plaincopy to clipboardprint?
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web.UI;
namespace Template
{
public class TemplateEngine:IDisposable
{
private UserControl _uc;
private TemplateBody _tpl;
public TemplateEngine()
{
_uc = new UserControl();
}
/// <summary>
/// 載入一個模板
/// </summary>
/// <param name="path">這個路徑為相對路徑</param>
public void Load(string path)
{
_tpl = _uc.LoadControl(path) as TemplateBody;
if (_tpl == null)
{
throw (new ArgumentException(path));
}
}
/// <summary>
/// 控制展示
/// </summary>
/// <returns>返回產生的字串</returns>
public string Render()
{
TextWriter tw = new StringWriter();
Render(tw);
return tw.ToString();
}
/// <summary>
/// 展示模板
/// </summary>
/// <param name="writer">TextWriter對象,可以傳Response.Output</param>
public void Render(TextWriter writer)
{
HtmlTextWriter htw = new HtmlTextWriter(writer);
_tpl.RenderControl(htw);
}
/// <summary>
/// 增加一個顯示資料的上下文
/// </summary>
/// <param name="key"></param>
/// <param name="obj"></param>
public void AddContext(string key, object obj)
{
_tpl.ViewData.Add(key, obj);
}
public object this[string key]
{
get{
object ret;
_tpl.ViewData.TryGetValue(key, out ret);
return ret;
}
set { AddContext(key, value); }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (disposing)
{
_uc.Dispose();
}
}
~TemplateEngine()
{
Dispose(false);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web.UI;
namespace Template
{
public class TemplateEngine:IDisposable
{
private UserControl _uc;
private TemplateBody _tpl;
public TemplateEngine()
{
_uc = new UserControl();
}
/// <summary>
/// 載入一個模板
/// </summary>
/// <param name="path">這個路徑為相對路徑</param>
public void Load(string path)
{
_tpl = _uc.LoadControl(path) as TemplateBody;
if (_tpl == null)
{
throw (new ArgumentException(path));
}
}
/// <summary>
/// 控制展示
/// </summary>
/// <returns>返回產生的字串</returns>
public string Render()
{
TextWriter tw = new StringWriter();
Render(tw);
return tw.ToString();
}
/// <summary>
/// 展示模板
/// </summary>
/// <param name="writer">TextWriter對象,可以傳Response.Output</param>
public void Render(TextWriter writer)
{
HtmlTextWriter htw = new HtmlTextWriter(writer);
_tpl.RenderControl(htw);
}
/// <summary>
/// 增加一個顯示資料的上下文
/// </summary>
/// <param name="key"></param>
/// <param name="obj"></param>
public void AddContext(string key, object obj)
{
_tpl.ViewData.Add(key, obj);
}
public object this[string key]
{
get{
object ret;
_tpl.ViewData.TryGetValue(key, out ret);
return ret;
}
set { AddContext(key, value); }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (disposing)
{
_uc.Dispose();
}
}
~TemplateEngine()
{
Dispose(false);
}
}
}
TemplateEngine 是負責顯示的類,核心代碼也就是調用了RenderControl函數.
下面是具體使用:
1.建立一個web工程,注意其他工程可能不支援.
2.添加預設頁面Default.aspx
3.根目錄添加一個TemplateTest.ascx的模板檔案 副檔名預設是ascx,如果需要更改別的副檔名的話需要在web.config裡在compilation節點增加下列代碼:
view plaincopy to clipboardprint?
<buildProviders>
<add extension=".view" type="System.Web.Compilation.UserControlBuildProvider"/>
</buildProviders>
<buildProviders>
<add extension=".view" type="System.Web.Compilation.UserControlBuildProvider"/>
</buildProviders>
4.直接運行就可以.
Default.aspx代碼:
view plaincopy to clipboardprint?
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Template;
namespace TemplateDemo
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TemplateEngine te = new TemplateEngine();
te.Load("TemplateTest.ascx");
te.AddContext("Text", "Super Man");
te.Render(Response.Output);
}
}
}
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Template;
namespace TemplateDemo
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TemplateEngine te = new TemplateEngine();
te.Load("TemplateTest.ascx");
te.AddContext("Text", "Super Man");
te.Render(Response.Output);
}
}
}
TemplateTest.ascx代碼:
view plaincopy to clipboardprint?
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TemplateBody.cs" Inherits="Template.TemplateBody" %>
<% for (int i = 0; i < 10; i++){
%>
<%=ViewData["Text"]%>
<% }%>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TemplateBody.cs" Inherits="Template.TemplateBody" %>
<% for (int i = 0; i < 10; i++){
%>
<%=ViewData["Text"]%>
<% }%>
記住,模板必須要加這個頭:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TemplateBody.cs" Inherits="Template.TemplateBody" %>
下面是顯示結果:
Super Man Super Man Super Man Super Man Super Man Super Man Super Man Super Man Super Man Super Man
需要改進的地方:
目前模板只支援相對路徑,因為.net他對檔案進行緩衝處理,這樣運行一次模板後即編譯模板並進行緩衝,如果檔案被更改將重新編譯,提高效率.
如果您需要從資料庫或者從一個Stream裡載入模板的話,需要重寫VirtualPathProvide,並且重寫判斷模板被更改的函數CacheDependency,還有擷取虛擬檔案的函數GetFile, 這樣很容易實現從任何地方擷取模板.如果您有興趣可以進行改進,完善.
本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/baoaya/archive/2009/07/27/4384178.aspx