/// <summary> /// 使用RazorEngine编译cshtml页面.返回静态内容 /// </summary> /// <param name="temps">temps是一个以路径为键,cshtml文件内容为值的字典.它包含了一个要被编译的cshtml主文件以及其引用的1个母板页和0~多个片段页.</param> /// <param name="mainCshtmlKey">要编译的主cshtml模板文件在temps中的key</param> /// <returns></returns> private static string RazorRun(Dictionary <string, string> temps, string mainCshtmlKey, object model = null) { // 添加要编译的cshtml文件,包括其引用的母板页和片段页 foreach (string key in temps.Keys) { // 如果文件有变化才重新添加模板和编译,因为编译时间比较长 if (!RazorCacheHelpers.IsChange(key, temps[key])) { continue; } // 键是文件的相对路径名,是固定的,每个cshtml的路径是唯一的. ITemplateKey k = serveice.GetKey(key); // 先删除这个键,再添加之.由于键固定,不删除的话,会报键重复. ((DelegateTemplateManager)config.TemplateManager).RemoveDynamic(k); // 添加模板,以键为模板名,以cshtml内容为模板内容 serveice.AddTemplate(k, temps[key]); // 编译之.由于键固定,如果不编译的话,就会使用上一次编译后的缓存(与这固定键对应的缓存).所以添加模板后,一定要重新编译. serveice.Compile(k); } // MainCshtmlKey是cshtml主页面,生成html时,必须以主cshtml模板的名. if (model == null) { return(serveice.Run(serveice.GetKey(mainCshtmlKey))); } return(serveice.Run(serveice.GetKey(mainCshtmlKey), null, model)); }
public RazorTemplateLoadResult LoadTemplate(string templateContents) { _templateKey = Guid.NewGuid().ToString(); _razorEngineService.AddTemplate(_templateKey, templateContents); RazorTemplateLoadResult razorTemplateLoadResult; try { _razorEngineService.Compile(_templateKey); razorTemplateLoadResult = new RazorTemplateLoadResult(RazorTemplateLoadResult.LoadResultStatus.Success); } catch (TemplateParsingException ex) { razorTemplateLoadResult = new RazorTemplateLoadResult( RazorTemplateLoadResult.LoadResultStatus.CodeGenerationFailed, new[] { $"Code Generation Error: {ex.Message} (at line {ex.Line}, column {ex.Column}" }); } catch (TemplateCompilationException ex) { razorTemplateLoadResult = new RazorTemplateLoadResult( RazorTemplateLoadResult.LoadResultStatus.CodeCompilationFailed, ex.CompilerErrors.Select(e => $"Code Compilation Error: {e.ErrorNumber}: {e.ErrorText} (at line {e.Line}, column {e.Column})").ToArray()); } catch (Exception ex) { razorTemplateLoadResult = new RazorTemplateLoadResult( RazorTemplateLoadResult.LoadResultStatus.CodeCompilationFailed, new[] { $"Exception while compiling template: {ex}" }); } return(razorTemplateLoadResult); }
public string Render <TModel>(CompilerConfiguration configuration, FilePath templatePath, TModel model) where TModel : TemplateViewModel { lock (_lock) { var templateName = templatePath.FullPath; if (!_engine.IsTemplateCached(templateName, typeof(TModel))) { templatePath = configuration.Root.CombineWithFilePath(templatePath); // Make sure the template exist. if (!_fileSystem.Exist(templatePath)) { const string format = "The template '{0}' do not exist."; var message = string.Format(format, templatePath.FullPath); throw new InvalidOperationException(message); } using (var stream = _fileSystem.GetFile(templatePath).OpenRead()) using (var reader = new StreamReader(stream)) { // Read the template and compile it. var template = reader.ReadToEnd(); _engine.AddTemplate(templateName, template); _engine.Compile(templateName, typeof(TModel)); } } return(_engine.Run(templateName, typeof(TModel), model)); } }
public RazorEngine() { var emailLayoutTemplate = GetManifestResource("Finastra.Hackathon.Emails.Templates.EmailLayout.cshtml"); var pdfLayoutTemplate = GetManifestResource("Finastra.Hackathon.Reports.Templates.ReportLayout.cshtml"); var config = new TemplateServiceConfiguration() { DisableTempFileLocking = true, CachingProvider = new DefaultCachingProvider(t => { _cachedFilePaths.Add(t); }), EncodedStringFactory = new RawStringFactory() }; RazorEngineService = global::RazorEngine.Templating.RazorEngineService.Create(config); RazorEngineService.AddTemplate("EmailLayout", emailLayoutTemplate); RazorEngineService.AddTemplate("ReportLayout", pdfLayoutTemplate); }
/// <summary> /// Adds and compiles a new template using the specified <paramref name="templateSource"/> and returns a <see cref="TemplateRunner{TModel}"/>. /// </summary> /// <typeparam name="TModel">The model type</typeparam> /// <param name="service"></param> /// <param name="templateSource"></param> /// <param name="name"></param> /// <returns></returns> public static ITemplateRunner <TModel> CompileRunner <TModel>(this IRazorEngineService service, string templateSource, string name) { var key = service.GetKey(name); service.AddTemplate(key, templateSource); service.Compile(key, typeof(TModel)); return(new TemplateRunner <TModel>(service, key)); }
private void CacheViews(IRazorEngineService razor) { razor.AddTemplate("team-list", View.Get("TeamList.cshtml")); razor.AddTemplate("team-info", View.Get("Team.cshtml")); razor.AddTemplate("individual-game-record-list", View.Get("IndividualGameRecordList.cshtml")); razor.AddTemplate("game-record-list", View.Get("GameRecordList.cshtml")); razor.AddTemplate("season-record-list", View.Get("SeasonRecordList.cshtml")); razor.AddTemplate("career-record-list", View.Get("CareerRecordList.cshtml")); razor.AddTemplate("streak-record-list", View.Get("StreakRecordList.cshtml")); razor.AddTemplate("home", View.Get("Home.cshtml")); }
public string Transform <T>(string template, T model) { var templateKey = template.GetHashCode().ToString(); if (!engine.IsTemplateCached(templateKey, typeof(T))) { engine.AddTemplate(templateKey, template); engine.Compile(templateKey, typeof(T)); } return(engine.Run(templateKey, typeof(T), model)); }
/// <summary> /// 预编译模板 /// </summary> /// <param name="sFileStr"></param> /// <param name="sKey"></param> /// <returns></returns> public static bool PrevCompileTemplate(string sKey, string sTemplateStr) { try { service.AddTemplate(sKey, sTemplateStr); service.Compile(sKey); return(true); } catch (Exception ex) { logger.Info(ex.Message); logger.Fatal(ex); return(false); } }
/// <summary> /// 编译并执行 /// </summary> /// <param name="name">模板名称</param> /// <param name="source">模板提供者</param> /// <param name="model">模型</param> /// <returns></returns> public static string RunCompile(string name, ITemplateSource source, object model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } lock (syncRoot) { if (templateNames.Add(name) == true) { razor.AddTemplate(name, source); razor.Compile(name); } } return(razor.RunCompile(name, model.GetType(), model)); }
public RazorTemplateService(string templatesNamespace, string outputDirectory) { _outputDirectory = outputDirectory; var templateConfig = new TemplateServiceConfiguration { DisableTempFileLocking = true, EncodedStringFactory = new RawStringFactory(), CachingProvider = new DefaultCachingProvider(x => { }) }; _razor = RazorEngineService.Create(templateConfig); var templateNames = ResourceHelper.GetResourceNames(templatesNamespace); foreach (var templateName in templateNames.Where(name => name.EndsWith(".cshtml"))) { var fileName = Path .GetFileNameWithoutExtension(templateName.Remove(0, templatesNamespace.Length + 1)) .Replace('.', '/'); _razor.AddTemplate(fileName, ResourceHelper.GetStringResource(templateName)); _razor.Compile(fileName); } }
public string GetResult([NotNull] HttpRequestMessage request, [CanBeNull] object model) { var lastWriteTimeUtc = File.GetLastWriteTimeUtc(templatePath); if (cachedLastWriteTimeUtc != lastWriteTimeUtc) { lock (locker) { if (cachedLastWriteTimeUtc != lastWriteTimeUtc) { var template = File.ReadAllText(templatePath); var templateSource = new LoadedTemplateSource(template, templatePath); templateKey = new NameOnlyTemplateKey(templatePath + Guid.NewGuid(), ResolveType.Global, null); razor.AddTemplate(templateKey, templateSource); razor.Compile(templateKey, modelType); cachedLastWriteTimeUtc = lastWriteTimeUtc; } } } var viewBag = new DynamicViewBag(); viewBag.AddValue("__request", request); return(razor.Run(templateKey, modelType, model, viewBag)); }
public void Init() { //load file setting with config in header RazorTemplate = FileTemplateManager.LoadFileTemplate(_filePath, _fileContent); //create config for razor engine //http://antaris.github.io/RazorEngine/ var config = new TemplateServiceConfiguration(); config.EncodedStringFactory = new RawStringFactory(); config.BaseTemplateType = typeof(CustomTemplateBase <>); config.TemplateManager = new DelegateTemplateManager(); var referenceResolver = new MyIReferenceResolver(); referenceResolver.DllFolder = RazorTemplate.InputDllFolder; config.ReferenceResolver = referenceResolver; _engine = RazorEngineService.Create(config); _templateKey = Engine.Razor.GetKey(MyTemplateKey.MAIN_TEMPLATE); //setup viewbag input Folder for render partial _viewBag = new DynamicViewBag(); _viewBag.AddValue("InputFolder", RazorTemplate.InputFolder); //check template is compile if (!_engine.IsTemplateCached(_templateKey, null)) { //add include template file var includeTemplate = new StringBuilder(); foreach (var filepath in RazorTemplate.ListImportFile) { includeTemplate.Append(FileUtils.ReadFileContent(filepath)); } var data = RazorTemplate.TemplateData; data = includeTemplate.ToString() + data; _templateSource = new LoadedTemplateSource(data); _engine.AddTemplate(_templateKey, _templateSource); _engine.Compile(_templateKey, _modeldata.GetType()); } }
/// <summary> /// 有时候需要利用统一的布局/母版 /// </summary> public virtual void LoadLayout(string layoutTemplate) { _razor.AddTemplate("myLayout", File.ReadAllText(layoutTemplate)); }
/// <summary> /// See <see cref="RazorEngineService.Compile"/>. /// Convenience method which calls <see cref="RazorEngineService.AddTemplate"/> before calling <see cref="RazorEngineService.Compile"/>. /// </summary> /// <param name="service"></param> /// <param name="templateSource"></param> /// <param name="key"></param> /// <param name="modelType"></param> public static void Compile(this IRazorEngineService service, string templateSource, ITemplateKey key, Type modelType = null) { service.AddTemplate(key, templateSource); service.Compile(key, modelType); }
/// <summary> /// Adds a given template to the template manager as dynamic template. /// </summary> /// <param name="service"></param> /// <param name="name"></param> /// <param name="templateSource"></param> public static void AddTemplate(this IRazorEngineService service, string name, string templateSource) { service.AddTemplate(name, new LoadedTemplateSource(templateSource)); }
/// <summary> /// Adds a given template to the template manager as dynamic template. /// </summary> /// <param name="service"></param> /// <param name="key"></param> /// <param name="templateSource"></param> public static void AddTemplate(this IRazorEngineService service, ITemplateKey key, string templateSource) { service.AddTemplate(key, new LoadedTemplateSource(templateSource)); }
/// <summary> /// Adds a given template to the template manager as dynamic template. /// </summary> /// <param name="service"></param> /// <param name="name"></param> /// <param name="templateSource"></param> public static void AddTemplate(this IRazorEngineService service, string name, ITemplateSource templateSource) { var key = service.GetKey(name); service.AddTemplate(key, templateSource); }
/// <summary> /// See <see cref="RazorEngineService.RunCompile"/>. /// Convenience method which calls <see cref="RazorEngineService.AddTemplate"/> before calling <see cref="RazorEngineService.RunCompile"/>. /// Convenience method which creates a <see cref="TextWriter"/> and returns the result as string. /// </summary> /// <param name="service"></param> /// <param name="templateSource"></param> /// <param name="name"></param> /// <param name="modelType"></param> /// <param name="model"></param> /// <param name="viewBag"></param> /// <returns></returns> public static string RunCompile(this IRazorEngineService service, string templateSource, string name, Type modelType = null, object model = null, DynamicViewBag viewBag = null) { service.AddTemplate(name, templateSource); return(service.RunCompile(name, modelType, model, viewBag)); }
/// <summary> /// See <see cref="RazorEngineService.RunCompile"/>. /// Convenience method which calls <see cref="RazorEngineService.AddTemplate"/> before calling <see cref="RazorEngineService.RunCompile"/>. /// </summary> /// <param name="service"></param> /// <param name="templateSource"></param> /// <param name="name"></param> /// <param name="writer"></param> /// <param name="modelType"></param> /// <param name="model"></param> /// <param name="viewBag"></param> public static void RunCompile(this IRazorEngineService service, string templateSource, string name, TextWriter writer, Type modelType = null, object model = null, DynamicViewBag viewBag = null) { service.AddTemplate(name, templateSource); service.RunCompile(name, writer, modelType, model, viewBag); }
internal static RazorTemplateState CreateTemplateState(this IRazorEngineService engine, RazorTemplateKey key, RazorTemplateSource source) { engine.AddTemplate(key, source); return(new RazorTemplateState(engine, key, source)); }
/// <summary> /// Adds a given template to the template manager as dynamic template. /// </summary> public void AddTemplate(ITemplateKey key, ITemplateSource templateSource) { m_engineService.AddTemplate(key, templateSource); }
/// <summary> /// Adds a given template to the template manager as dynamic template. /// </summary> /// <param name="key"></param> /// <param name="templateSource"></param> public void AddTemplate(ITemplateKey key, ITemplateSource templateSource) { _proxy.AddTemplate(key, templateSource); }
public void AddTemplate(ITemplateKey key, ITemplateSource templateSource) { _origin.AddTemplate(key, templateSource); }
public void AddTemplate(ITemplateKey key, ITemplateSource templateSource) { _razor.AddTemplate(key, templateSource); }