為什麼要這麼做?
可是也有這些想法的人並不多
如Razor引擎淺析所述
保持模板功能
編譯? 你根本就找不到這一段代碼
首先
[csharp] view plaincopy
using System
using System
using System
第一步
[csharp]
public static Type Compile<T>(string template_path)
{
//准備臨時類名
var class_name =
var base_type = typeof(TemplateBase<>)
var template = File
var host = new RazorEngineHost(new CSharpRazorCodeLanguage()
{
DefaultBaseClass = base_type
DefaultClassName = class_name
DefaultNamespace =
GeneratedClassContext =
new GeneratedClassContext(
};
host
host
//生成代碼
CodeCompileUnit code;
using (var reader = new StringReader(template)) {
var generatedCode = new RazorTemplateEngine(host)
code = generatedCode
}
//准備編譯參數
var @params = new CompilerParameters
{
IncludeDebugInformation = false
TempFiles = new TempFileCollection(AppDomain
CompilerOptions =
GenerateInMemory = false
};
var assemblies = AppDomain
@params
//編譯
var provider = new CSharpCodeProvider()
var compiled = provider
if (compiled
var compileErrors = string
throw new ApplicationException(
}
//編譯成功後
return compiled
}
第二步就簡單多了
[csharp]
public static string Render<T>(T model
{
var type = Compile<T>(template_path)
//創建視圖實例
var instance = (TemplateBase<T>)Activator
//執行模板(把數據嵌入文件)
instance
instance
//輸出最終結果
var result = instance
return result;
}
最後
[csharp]
public abstract class TemplateBase
{
public string Layout { get; set; }
public UrlHelper Url { get; set; }
public Func<string> RenderBody { get; set; }
public string Path { get; internal set; }
public string Result { get { return Writer
protected TemplateBase()
{
}
public TextWriter Writer
{
get
{
if(writer==null)
{writer = new StringWriter()
}
return writer;
}
set {
writer = value;
}
}
private TextWriter writer;
public void Clear() {
Writer
}
public virtual void Execute() { }
public void Write(object @object) {
if (@object == null) {
return;
}
Writer
}
public void WriteLiteral(string @string) {
if (@string == null) {
return;
}
Writer
}
public static void WriteLiteralTo(TextWriter writer
if (literal == null) {
return;
}
writer
}
public static void WriteTo(TextWriter writer
if (obj == null) {
return;
}
writer
}
}
public abstract class TemplateBase<T> :TemplateBase
{
public T Model { get; set; }
}
From:http://tw.wingwit.com/Article/program/net/201311/12710.html