/// <summary> /// Includes the template with the specified key /// </summary> /// <param name="key">Key used to resolve a template</param> /// <param name="model">Template model</param> public async Task IncludeAsync(string key, object model = null) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key)); } if (this.PageLookup == null) { throw new RazorLightException("Can't locate a page as PageLookup is not set"); } PageLookupResult pageResult = PageLookup.GetPage(key); if (pageResult.Success) { TemplatePage page = pageResult.ViewEntry.PageFactory(); page.PageContext = new PageContext(this.PageContext.ViewBag) { Writer = this.PageContext.Writer }; if (model != null) { var modelTypeInfo = new ModelTypeInfo(model.GetType()); page.PageContext.ModelTypeInfo = modelTypeInfo; object pageModel = modelTypeInfo.CreateTemplateModel(model); page.SetModel(pageModel); } await page.ExecuteAsync(); } }
/// <summary> /// Generates razor template by parsing given <param name="templateSource" /> /// </summary> /// <param name="templateSource"></param> /// <param name="modelTypeInfo"></param> /// <returns></returns> public string GenerateRazorTemplate(ITemplateSource templateSource, ModelTypeInfo modelTypeInfo) { var host = new RazorLightHost(null); if (modelTypeInfo != null) { host.DefaultModel = modelTypeInfo.TemplateTypeName; } return(Configuration.RazorTemplateCompiler.CompileTemplate(host, templateSource)); }
/// <summary> /// Compiles a <see cref="ITemplateSource"/> with a specified <see cref="ModelTypeInfo"/> /// </summary> /// <param name="templateSource">Template source</param> /// <param name="modelTypeInfo">Model type information</param> /// <returns>Compiled type in succeded. Compilation errors on fail</returns> public CompilationResult CompileSource(ITemplateSource templateSource, ModelTypeInfo modelTypeInfo) { if (templateSource == null) { throw new ArgumentNullException(nameof(templateSource)); } string razorTemplate = GenerateRazorTemplate(templateSource, modelTypeInfo); var context = new CompilationContext(razorTemplate, Configuration.Namespaces); CompilationResult compilationResult = Configuration.CompilerService.Compile(context); return(compilationResult); }
/// <summary> /// Generates razor template by parsing given <param name="templateSource" /> /// </summary> /// <param name="templateSource"></param> /// <param name="modelTypeInfo"></param> /// <returns></returns> public string GenerateRazorTemplate(ITemplateSource templateSource, ModelTypeInfo modelTypeInfo) { var host = new RazorLightHost(null); //Set default model if (modelTypeInfo != null) { host.DefaultModel = modelTypeInfo.TemplateTypeName; } //Include namespaces if (Configuration.Namespaces != null) { foreach (string @namespace in Configuration.Namespaces) { host.NamespaceImports.Add(@namespace); } } return(Configuration.RazorTemplateCompiler.CompileTemplate(host, templateSource)); }