- public static string Render<T>(T model,string template_path)
- {
- var type = Compile<T>(template_path);
- //创建视图实例
- var instance = (TemplateBase<T>)Activator.CreateInstance(type);
- //执行模板(把数据嵌入文件)
- instance.Model = model;
- instance.Execute();
- //输出最终结果
- var result = instance.Result;
- return result;
- }
最后,看看视图模板类,一个基类和一个泛型基类,后者用于前类型Model
- 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.ToString(); } }
- protected TemplateBase()
- {
- }
- public TextWriter Writer
- {
- get
- {
- if(writer==null)
- {writer = new StringWriter();
- }
- return writer;
- }
- set {
- writer = value;
- }
- }
- private TextWriter writer;
- public void Clear() {
- Writer.Flush();
- }
- public virtual void Execute() { }
- public void Write(object @object) {
- if (@object == null) {
- return;
- }
- Writer.Write(@object);
- }
- public void WriteLiteral(string @string) {
- if (@string == null) {
- return;
- }
- Writer.Write(@string);
- }
- public static void WriteLiteralTo(TextWriter writer, string literal) {
- if (literal == null) {
- return;
- }
- writer.Write(literal);
- }
- public static void WriteTo(TextWriter writer, object obj) {
- if (obj == null) {
- return;
- }
- writer.Write(obj);
- }
- }
- public abstract class TemplateBase<T> :TemplateBase
- {
- public T Model { get; set; }
- }
原