private void GenerateHtml(IRazorEngineService service) { var SampleTemplate = File.ReadAllText("SampleTemplate.cshtml"); var SubSample = File.ReadAllText("SubSample.cshtml"); //service.AddTemplate("part", SubSample); // If you leave the second and third parameters out the current model will be used. // If you leave the third we assume the template can be used for multiple types and use "dynamic". // If the second parameter is null (which is default) the third parameter is ignored. // To workaround in the case you want to specify type "dynamic" without specifying a model use Include("p", new object(), null) //service.AddTemplate("template", SampleTemplate); service.Compile(SampleTemplate, "template", typeof(MyModel)); service.Compile(SubSample, "part", typeof(SubModel)); var result = service.Run("template", typeof(MyModel), new MyModel { SubModelTemplateName = "part", ModelProperty = "model1<@><b>rob</b></@>.com <", RawProperty = "model1<@><b>rob</b></@>.com <", SubModel = new SubModel { SubModelProperty = "submodel2" } }); Console.WriteLine("Result is: {0}", result); DisplayHtml(result); }
/// <summary> /// Компиляция и кеширование шаблонов для последующего использования /// </summary> /// <param name="service"></param> private static void PrepareTemplates(IRazorEngineService service) { service.Compile("Emails/Invite", typeof(InviteEmailModel)); service.Compile("Emails/Registered", typeof(RegisteredEmailModel)); service.Compile("Emails/ChangePassword", typeof(ChangePasswordEmailModel)); service.Compile("Emails/RestorePassword", typeof(RestorePasswordEmailModel)); }
/// <summary> /// RazorEngineのテンプレートを初期化する /// </summary> /// <param name="useCaseCatalogTemplate">ユースケースカタログテンプレート文字列</param> /// <param name="useCaseScenarioSetTemplate">ユースケースシナリオセットテンプレート文字列</param> private void InitializeRazorEngineTemplate(string useCaseCatalogTemplate, string useCaseScenarioSetTemplate) { try { razorEngineService.Compile(useCaseCatalogTemplate, "UseCaseCatalogTemplateKey", typeof(UseCaseCatalog)); razorEngineService.Compile(useCaseScenarioSetTemplate, "UseCaseScenarioSetTemplateKey", typeof(UseCaseScenarioSet)); } catch (TemplateCompilationException e) { throw new ApplicationException(Resources.Resources.Exception_RazorEngineTemplateCompilation, e); } }
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)); } }
/// <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 override void PreCompile(View view) { if (!_razor.IsTemplateCached(view.Hash, view.ModelType.Type)) { _razor.Compile(view.Source, view.Hash, view.ModelType.Type); } }
public RazorTransform(IContext context) : base(context, context.Field.Type) { _input = MultipleInput(); var key = GetHashCode(context.Transform.Template, _input); if (!Cache.TryGetValue(key, out _service)) { var config = new TemplateServiceConfiguration { DisableTempFileLocking = true, EncodedStringFactory = Context.Transform.ContentType == "html" ? (IEncodedStringFactory) new HtmlEncodedStringFactory() : new RawStringFactory(), Language = Language.CSharp, CachingProvider = new DefaultCachingProvider(t => { }) }; _service = RazorEngineService.Create(config); } try { _service.Compile(Context.Transform.Template, Context.Key, typeof(ExpandoObject)); Cache[key] = _service; } catch (Exception ex) { Context.Warn(Context.Transform.Template.Replace("{", "{{").Replace("}", "}}")); Context.Warn(ex.Message); throw; } }
/// <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)); }
public void PrecompileTemplates() { if (precompiled) { return; } Log.Info("Begin compiling email templates."); var baseDir = new DirectoryInfo(Path.Combine(BaseDirectory, "Views")); var files = baseDir.GetFileSystemInfos("*.cshtml", SearchOption.TopDirectoryOnly); foreach (var file in files) { Log.Info($"Compiling {file.Name}"); _razor.Compile(Path.GetFileNameWithoutExtension(file.Name)); } Log.Info("End compiling email templates."); precompiled = true; }
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)); }
public string Generate(TModel model, TemplateContext templateContext) { if (!compiled) { razorEngineService.Compile(templateKey, typeof(TModel)); compiled = true; } var viewBag = new DynamicViewBag(); viewBag.AddValue("TemplateContext", templateContext); return(razorEngineService.Run(templateKey, typeof(TModel), model, viewBag)); }
public string Render(string key, Type modelType, object model) { TemplateState templateState; if (!_TemplateStates.TryGetValue(key, out templateState)) { throw new ApplicationException("Unable to find template in cache"); } var cacheFileInfo = templateState.FileInfo; string templatePath = cacheFileInfo.FullName; var fileInfo = new FileInfo(templatePath); if (!templateState.Compiled || fileInfo.LastWriteTimeUtc > cacheFileInfo.LastWriteTimeUtc) { try { Console.WriteLine("Recompiling {0}", templatePath); string source = File.ReadAllText(templatePath); var templateKey = _Engine.GetKey(key); _TemplateManager.RemoveDynamic(templateKey); _CachingProvider.InvalidateCache(templateKey); _Engine.Compile(source, key); templateState.FileInfo = fileInfo; templateState.Compiled = true; } catch (Exception exception) { templateState.Compiled = false; var errors = GetTemplateErrors(exception, templatePath); string message = string.Join("\n", errors); throw new ApplicationException(message); } } string markup = _Engine.Run(key, modelType, model); return(markup); }
/// <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 HtmlReceiptBuilder(string template, string key) { // Removes all new lines, line feeds, tabs template = new string[] { "\n", "\r", "\t" }.Aggregate(template, (current, c) => current.Replace(c, string.Empty)); _key = key; _templateService = RazorEngineService.Create( new TemplateServiceConfiguration() { Namespaces = new HashSet <string> { "BikeDistributor.Helpers", "System.Linq" } }); _templateService.Compile(template, key, typeof(OrderViewModel)); }
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>Compiles the specified template and caches it.</summary> public void Compile(ITemplateKey key, Type modelType = null) { m_engineService.Compile(key, modelType); }
public void Compile(ITemplateKey key, Type modelType = null) { CheckModelType(modelType); _origin.Compile(key, modelType); }
/// <summary> /// Compiles the specified template and caches it. /// </summary> /// <param name="key">The key of the template.</param> /// <param name="modelType">The model type.</param> public void Compile(ITemplateKey key, Type modelType = null) { _proxy.Compile(key, modelType); }
/// <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> /// See <see cref="RazorEngineService.Compile"/>. /// </summary> /// <param name="service"></param> /// <param name="name"></param> /// <param name="modelType"></param> public static void Compile(this IRazorEngineService service, string name, Type modelType = null) { service.Compile(service.GetKey(name), modelType); }
public void Initialize() { string templateSource; var stream = typeof(Program).Assembly.GetManifestResourceStream("DescentGlovePie.Generator.Views." + TemplateName); if (stream == null) throw new ApplicationException("Missing assembly resource for Razor view " + TemplateName); using (stream) { templateSource = new StreamReader(stream).ReadToEnd(); } // This template uses iSynaptic.Commons, so let's make sure the runtime loads it templateSource = templateSource.ToMaybe().Value; var config = new TemplateServiceConfiguration { EncodedStringFactory = new RawStringFactory() }; _razor = RazorEngineService.Create(config); _razor.Compile(templateSource, TemplateName, typeof(MapInfo)); }
/// <summary> /// 预编译模板 /// </summary> /// <param name="key">键</param> /// <param name="template">模板内容</param> public void Compile(string key, string template) { razor.Compile(template, key); }