private void AssertViewCanBeCompiled(string content, string viewPath, TemplateService processor) { try { processor.Compile(content, null, viewPath); } catch (TemplateCompilationException ex) { var message = new StringBuilder() .AppendFormat("The view: {0} cannot be compiled because of the following errors:", viewPath); foreach (var error in ex.Errors) { if (!error.IsWarning) { message.AppendLine().AppendFormat( CultureInfo.InvariantCulture, "Error: {0} - {1}", error.ErrorNumber, error.ErrorText); } } Assert.Fail(message.ToString()); } }
//public static string CompileTemplate(string templatestring, IPackage package) //{ // if (package == null) { // throw new ArgumentNullException ("package"); // } // if (string.IsNullOrEmpty (templatestring)) { // throw new ArgumentException ("templatestring cannot be null or empty.", "templatestring"); // } // string result = Razor.Parse(templatestring, package); // return result; //} //public static void CompileFile(string templatepath, string outpath, IPackage package) //{ // if (package == null) { // throw new ArgumentNullException ("package"); // } // if (string.IsNullOrEmpty (templatepath)) { // throw new ArgumentException ("templatepath cannot be null or empty.", "templatepath"); // } // if (string.IsNullOrEmpty (outpath)) { // throw new ArgumentException ("outpath cannot be null or empty.", "outpath"); // } // string template = IO.File.ReadAllText (templatepath); // string result = Razor.Parse(template, package); // IO.File.WriteAllText (outpath, result); //} //public static void CompileFile(string templatepath, IEnumerable<string> parentpaths, string outpath, IPackage package) //{ // using (TemplateService service = new TemplateService()) // { // foreach (string path in parentpaths) // { // string tpl = IO.File.ReadAllText (path); // service.Compile(tpl, typeof(object), IO.Path.GetFileNameWithoutExtension(path)); // } // string tplstring = IO.File.ReadAllText (templatepath); // string result = service.Parse(tplstring, package, null, null); // IO.File.WriteAllText (outpath, result); // } //} public static void CompileFile(string templatedir, string viewname, IPackage package, string outpath) { IO.DirectoryInfo indir = new IO.DirectoryInfo(templatedir); IEnumerable <IO.FileInfo> allviewfiles = indir.GetFiles("*.cshtml", IO.SearchOption.AllDirectories); using (TemplateService service = new TemplateService()) { IO.FileInfo viewfile = null; foreach (IO.FileInfo f in allviewfiles) { string fname = IO.Path.GetFileNameWithoutExtension(f.FullName); if (fname != viewname) { string tpl = IO.File.ReadAllText(f.FullName); service.Compile(tpl, typeof(object), fname); } else { viewfile = f; } } if (viewfile == null) { throw new ArgumentException("A view named " + viewname + " could not be found.", "viewname"); } string tplstring = IO.File.ReadAllText(viewfile.FullName); string result = service.Parse(tplstring, package, null, null); IO.File.WriteAllText(outpath, result); } }
protected override async Task OnExecute() { var dc = GetDatacenter(required: true); var service = dc.GetService(Service); if (service == null) { await Console.WriteErrorLine(Strings.Config_GenerateCommand_NoSuchService, Service, dc.FullName); return; } // Get the config template for this service if (dc.Environment.ConfigTemplates == null) { await Console.WriteErrorLine(Strings.Config_GenerateCommand_NoTemplateSource, dc.Environment.FullName); } else { if (!String.Equals(dc.Environment.ConfigTemplates.Type, FileSystemConfigTemplateSource.AbsoluteAppModelType, StringComparison.OrdinalIgnoreCase)) { await Console.WriteErrorLine(Strings.Config_GenerateCommand_UnknownConfigTemplateSourceType, dc.Environment.ConfigTemplates.Type); } var configSource = new FileSystemConfigTemplateSource(dc.Environment.ConfigTemplates.Value); var configTemplate = configSource.ReadConfigTemplate(service); if (String.IsNullOrEmpty(configTemplate)) { await Console.WriteErrorLine(Strings.Config_GenerateCommand_NoTemplate, service.FullName); } else { var secrets = await GetEnvironmentSecretStore(Session.CurrentEnvironment); // Render the template var engine = new TemplateService(new TemplateServiceConfiguration() { BaseTemplateType = typeof(ConfigTemplateBase), Language = Language.CSharp }); await Console.WriteInfoLine(Strings.Config_GenerateCommand_CompilingConfigTemplate, service.FullName); engine.Compile(configTemplate, typeof(object), "configTemplate"); await Console.WriteInfoLine(Strings.Config_GenerateCommand_ExecutingTemplate, service.FullName); string result = engine.Run("configTemplate", new ConfigTemplateModel(secrets, service), null); // Write the template if (String.IsNullOrEmpty(OutputFile)) { await Console.WriteDataLine(result); } else { File.WriteAllText(OutputFile, result); await Console.WriteInfoLine(Strings.Config_GenerateCommand_GeneratedConfig, OutputFile); } } } }
public Message Generate(string messageCode, object model, string locale) { if (model == null) { throw new NullReferenceException("model"); } try { var cacheName = string.Format("{0}.{1}", messageCode, locale); if (!_service.HasTemplate(cacheName)) { var template = _templateLocator.GetTemplate(messageCode, locale); _service.Compile(template, typeof(MessageTemplate <>), cacheName); } var resolvedTemplate = _service.Resolve(cacheName, model); var result = _service.Run(resolvedTemplate, null); return(new Message { Subject = ((IMessageTemplate)resolvedTemplate).Subject, Body = result }); } catch (TemplateCompilationException tce) { _log.Error("Template compilation error", tce); throw; } }
public void Compile(string template, Type type, string cacheName) { var config = GetConfig(); var templateService = new TemplateService(config); templateService.Compile(template, type, cacheName); }
/// <summary> /// 生成静态页(带母版) /// </summary> /// <returns></returns> public bool ToPage(dynamic model) { CompilerServiceBuilder.SetCompilerServiceFactory(new DefaultCompilerServiceFactory()); using (var service = new TemplateService()) { string master = System.IO.File.ReadAllText(MasterUrl, OutputEncoding); string content = System.IO.File.ReadAllText(TemplateUrl, OutputEncoding); service.Compile(content, model.GetType(), MasterMapper); string result = service.Parse(master, model); if (File.Exists(SaveUrl)) { File.Delete(SaveUrl); } using (FileStream stream = new FileStream(SaveUrl, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { Byte[] info = OutputEncoding.GetBytes(result); stream.Write(info, 0, info.Length); stream.Flush(); stream.Close(); return(true); } } return(false); }
public void Issue11_TemplateServiceShouldCompileModellessTemplate() { using (var service = new TemplateService()) { const string template = "<h1>Hello World</h1>"; service.Compile(template, null, "issue11"); } }
public void Issue7_ViewBagShouldPersistThroughLayout() { using (var service = new TemplateService()) { const string layoutTemplate = "<h1>@ViewBag.Title</h1>@RenderSection(\"Child\")"; const string childTemplate = "@{ Layout = \"Parent\"; ViewBag.Title = \"Test\"; }@section Child {}"; service.Compile(layoutTemplate, null, "Parent"); string result = service.Parse(childTemplate, null, null, null); Assert.That(result.StartsWith("<h1>Test</h1>")); } }
public void TemplateService_CanPrecompileTemplate_WithNoModel() { using (var service = new TemplateService()) { const string template = "Hello World"; const string expected = "Hello World"; service.Compile(template, null, "test"); string result = service.Run("test", null, null); Assert.That(result == expected, "Result does not match expected."); } }
public void CompiledRazorView_Should_Render_Compiled_Template_When_TemplateService_Is_Provided() { var templateService = new TemplateService(); templateService.Compile("@model object\r\nHello World!", "test"); var view = new CompiledRazorView("test", templateService); var context = new Mock<ViewContext>(); context.Setup(c => c.ViewData).Returns(new ViewDataDictionary(new object())); using (var writer = new StringWriter()) { view.Render(context.Object, writer); var content = writer.GetStringBuilder().ToString(); Assert.Equal("Hello World!", content); } }
public void TemplateService_CanPrecompileTemplate_WithNoModelAndANonGenericBase() { var config = new TemplateServiceConfiguration { BaseTemplateType = typeof(NonGenericTemplateBase) }; using (var service = new TemplateService(config)) { const string template = "<h1>@GetHelloWorldText()</h1>"; const string expected = "<h1>Hello World</h1>"; service.Compile(template, null, "test"); string result = service.Run("test", null, null); Assert.That(result == expected, "Result does not match expected."); } }
private void ProcessSubContent(Match match, TemplateService service, dynamic model) { var subName = match.Groups[1].Value; string subContent; if (this.Cache.TryGetValue(subName, out subContent)) { // Process inputs subContent = this.ProcessInputs(subContent); // Recursively process it and add to the service ProcessContent(subContent, service, model); // Compile the template service.Compile(subContent, typeof(AssetHeader), subName); } }
public void TemplateService_CanPrecompileTemplate_WithSimpleModel() { using (var service = new TemplateService()) { const string template = "Hello @Model.Forename"; const string expected = "Hello Matt"; var model = new Person { Forename = "Matt" }; service.Compile(template, typeof(Person), "test"); string result = service.Run("test", model, null); Assert.That(result == expected, "Result does not match expected."); } }
public void Issue93_SectionParsing() { using (var service = new TemplateService()) { string parent = @"@RenderSection(""MySection"", false)"; string section_test_1 = "@{ Layout = \"ParentLayout\"; }@section MySection { My section content }"; string section_test_2 = "@{ Layout = \"ParentLayout\"; }@section MySection {\nMy section content\n}"; string section_test_3 = "@{ Layout = \"ParentLayout\"; }@section MySection {\nMy section content\na}"; string expected_1 = " My section content "; string expected_2 = "\nMy section content\n"; string expected_3 = "\nMy section content\na"; service.Compile(parent, null, "ParentLayout"); var result_1 = service.Parse(section_test_1, null, null, null); var result_2 = service.Parse(section_test_2, null, null, null); var result_3 = service.Parse(section_test_3, null, null, null); Assert.AreEqual(expected_1, result_1); Assert.AreEqual(expected_2, result_2); Assert.AreEqual(expected_3, result_3); } }
public void Issue6_ModelShouldBePassedToLayout() { using (var service = new TemplateService()) { const string layoutTemplate = "<h1>@Model.PageTitle</h1> @RenderSection(\"Child\")"; const string childTemplate = "@{ Layout = \"Parent\"; }@section Child {<h2>@Model.PageDescription</h2>}"; const string expected = "<h1>Test Page</h1> <h2>Test Page Description</h2>"; var model = new { PageTitle = "Test Page", PageDescription = "Test Page Description" }; var type = model.GetType(); service.Compile(layoutTemplate, type, "Parent"); string result = service.Parse(childTemplate, model, null, null); Assert.That(result == expected, "Result does not match expected: " + result); } }
public void Issue21_SubclassModelShouldBeSupportedInLayout() { using (var service = new TemplateService()) { const string parent = "@model RazorEngine.Tests.TestTypes.Person\n<h1>@Model.Forename</h1>@RenderSection(\"Child\")"; service.Compile(parent, null, "Parent"); const string child = "@{ Layout = \"Parent\"; }\n@section Child { <h2>@Model.Department</h2> }"; const string expected = "<h1>Matt</h1> <h2>IT</h2> "; var model = new Employee { Age = 27, Department = "IT", Forename = "Matt", Surname = "Abbott" }; string result = service.Parse(child, model, null, null); Assert.That(result == expected, "Result does not match expected: " + result); } }
public void Compile(Type model) { Contract.Requires(model != null); if (String.IsNullOrWhiteSpace(Subject)) throw new ArgumentNullException("Subject"); if (String.IsNullOrWhiteSpace(Email)) throw new ArgumentNullException("Email"); if (String.IsNullOrWhiteSpace(MailFrom)) throw new ArgumentNullException("MailFrom"); if (String.IsNullOrWhiteSpace(NameFrom)) throw new ArgumentNullException("NameFrom"); templateService = new TemplateService(new TemplateServiceConfiguration { BaseTemplateType = typeof(IrisTemplateBase<>) }); templateService.Compile(Subject, model, "Subject"); templateService.Compile(Email, model, "Email"); templateService.Compile(MailFrom, model, "MailFrom"); templateService.Compile(NameFrom, model, "NameFrom"); templateService.Compile(HtmlBody, model, "HtmlBody"); if (ReplyTo != null) templateService.Compile(ReplyTo, model, "ReplyTo"); if (TextBody != null) templateService.Compile(TextBody, model, "TxtBody"); }
public void TemplateService_CanPrecompileTemplate_WithSimpleModel() { using (var service = new TemplateService()) { const string template = "Hello @Model.Forename"; const string expected = "Hello Matt"; var model = new Person { Forename = "Matt" }; service.Compile<Person>(template, "test"); string result = service.Run("test", model); Assert.That(result == expected, "Result does not match expected."); } }
public string RenderPageTemplate(int?pageTemplateId, PageRenderModel model) { var pageTemplate = GetById(pageTemplateId); var config = _templateServices.GetConfig(); using (var templateService = new TemplateService(config)) { /* * Get default master template for all content * This template is used for including some scripts or html for all page contents and file contents */ var defaultTemplate = GetDefaultTemplate(); var template = defaultTemplate.Content; template = CurlyBracketParser.ParseProperties(template); template = CurlyBracketParser.ParseRenderBody(template); var layout = TemplateServices.GetTemplateCacheName(defaultTemplate.Name, defaultTemplate.Created, defaultTemplate.Updated); if (Razor.Resolve(layout) == null) { templateService.Compile(template, typeof(PageRenderModel), layout); } /* * Loop all the parent template to compile and render layout */ if (pageTemplate != null) { // Using hierarchy to load all parent templates var pageTemplates = _pageTemplateRepository.GetAll().Where(t => pageTemplate.Hierarchy.Contains(t.Hierarchy)) .OrderBy(t => t.Hierarchy) .Select(t => new { t.Content, t.Name, t.Updated, t.Created }); if (pageTemplates.Any()) { foreach (var item in pageTemplates) { //Convert curly bracket properties to razor syntax template = CurlyBracketParser.ParseProperties(item.Content); //Insert master page for child template and parsing template = InsertMasterPage(template, layout); template = FormatMaster(template); template = templateService.Parse(template, model, null, null); template = ReformatMaster(template); //This used for re-cache the template layout = TemplateServices.GetTemplateCacheName(item.Name, item.Created, item.Updated); //Convert {RenderBody} to @RenderBody() for next rendering template = CurlyBracketParser.ParseRenderBody(template); if (Razor.Resolve(layout) == null) { templateService.Compile(template, typeof(PageRenderModel), layout); } } } } return(template); } }
public void TemplateService_CanPrecompileTemplate_WithNoModel() { using (var service = new TemplateService()) { const string template = "Hello World"; const string expected = "Hello World"; service.Compile(template, "test"); string result = service.Run("test"); Assert.That(result == expected, "Result does not match expected."); } }
public string RenderPageTemplate(int? pageTemplateId, PageRenderModel model) { var pageTemplate = GetById(pageTemplateId); var config = _templateServices.GetConfig(); using (var templateService = new TemplateService(config)) { /* * Get default master template for all content * This template is used for including some scripts or html for all page contents and file contents */ var defaultTemplate = GetDefaultTemplate(); var template = defaultTemplate.Content; template = CurlyBracketParser.ParseProperties(template); template = CurlyBracketParser.ParseRenderBody(template); var layout = TemplateServices.GetTemplateCacheName(defaultTemplate.Name, defaultTemplate.Created, defaultTemplate.Updated); if (Razor.Resolve(layout) == null) { templateService.Compile(template, typeof(PageRenderModel), layout); } /* * Loop all the parent template to compile and render layout */ if (pageTemplate != null) { // Using hierarchy to load all parent templates var pageTemplates = _pageTemplateRepository.GetAll().Where(t => pageTemplate.Hierarchy.Contains(t.Hierarchy)) .OrderBy(t => t.Hierarchy) .Select(t => new { t.Content, t.Name, t.Updated, t.Created }); if (pageTemplates.Any()) { foreach (var item in pageTemplates) { //Convert curly bracket properties to razor syntax template = CurlyBracketParser.ParseProperties(item.Content); //Insert master page for child template and parsing template = InsertMasterPage(template, layout); template = FormatMaster(template); template = templateService.Parse(template, model, null, null); template = ReformatMaster(template); //This used for re-cache the template layout = TemplateServices.GetTemplateCacheName(item.Name, item.Created, item.Updated); //Convert {RenderBody} to @RenderBody() for next rendering template = CurlyBracketParser.ParseRenderBody(template); if (Razor.Resolve(layout) == null) { templateService.Compile(template, typeof(PageRenderModel), layout); } } } } return template; } }
/// <summary> /// Pre-compiles the specified template and caches it using the specified name. /// </summary> /// <param name="template">The template to precompile.</param> /// <param name="modelType">The type of model used in the template.</param> /// <param name="name">The cache name for the template.</param> public static void Compile(string template, Type modelType, string name) { EnsureTemplateService(); service.Compile(template, modelType, name); }