/// <summary> /// Compiles and renders a template. /// </summary> /// <param name="path">The fully qualified path of the file to load.</param> /// <param name="context">The <see cref="TemplateContext"/>.</param> /// <returns></returns> public static string CompileFileAndExec(this TemplateContext context, string path) { var full = context.FindFullPath(path); if (full == null) { throw new Exception.TemplateException($"\"{ path }\" cannot be found."); } var template = context.Options.CompilerResults.GetOrAdd(full, (name) => { var res = context.Options.Loader.Load(path, context.Options.Encoding, context.Options.ResourceDirectories.ToArray()); if (res == null) { throw new Exception.TemplateException($"Path:\"{path}\", the file could not be found."); } if (string.IsNullOrEmpty(name)) { name = res.FullPath; } return(TemplateCompiler.Compile(name, res.Content, context.Options, (c) => context.CopyTo(c))); }); using (var sw = new System.IO.StringWriter()) { template.Render(sw, context); return(sw.ToString()); } }
/// <summary> /// Compiles and renders a template. /// </summary> /// <param name="path">The fully qualified path of the file to load.</param> /// <param name="context">The <see cref="TemplateContext"/>.</param> /// <returns></returns> public static IResult CompileFile(this TemplateContext context, string path) { var full = context.FindFullPath(path); if (full == null) { throw new TemplateException($"\"{ path }\" cannot be found."); } var template = context.Environment.Results.GetOrAdd(full, (fullName) => { var res = context.Load(fullName); if (res == null) { throw new TemplateException($"Path:\"{path}\", the file could not be found."); } return(context.Environment.Compile(fullName, res.Content, (c) => context.CopyTo(c))); }); return(template); }
/// <summary> /// 编译并执行模板 /// </summary> /// <param name="fileName">模板路径</param> /// <param name="ctx">TemplateContext</param> /// <returns></returns> public static string CompileFileAndExec(string fileName, TemplateContext ctx) { var full = ctx.FindFullPath(fileName); if (full == null) { throw new Exception.TemplateException($"\"{ fileName }\" cannot be found."); } var template = Runtime.Templates[full]; if (template == null) { template = CompileFile(full, full, (c) => ctx.CopyTo(c)); if (template == null) { throw new Exception.TemplateException($"\"{ fileName }\" compile error."); } } using (var sw = new System.IO.StringWriter()) { template.Render(sw, ctx); return(sw.ToString()); } }