public string GenerateOutput <TModel>(TModel model, string templateName) { if (compiledTemplateAssembly == null) { throw new InvalidOperationException("Templates have not been compiled."); } if (templateName == null) { throw new ArgumentNullException("templateName"); } RazorTemplateEntry entry = null; try { entry = templateItems[TranslateKey(typeof(TModel), templateName)]; } catch (KeyNotFoundException) { throw new ArgumentOutOfRangeException("No template has been registered under this model or name."); } var template = (RazorTemplateBase <TModel>)compiledTemplateAssembly.CreateInstance("RazorTemplateingSample." + entry.TemplateName + "Template"); template.Model = model; template.Execute(); var output = template.Buffer.ToString(); template.Buffer.Clear(); return(output); }
private static GeneratorResults GenerateCode(RazorTemplateEntry entry) { var host = new RazorEngineHost(new CSharpRazorCodeLanguage()); host.DefaultBaseClass = string.Format("RazorTemplateingSample.RazorTemplating.RazorTemplateBase<{0}>", entry.ModelType.FullName); host.DefaultNamespace = "RazorTemplateingSample"; host.DefaultClassName = entry.TemplateName + "Template"; host.NamespaceImports.Add("System"); GeneratorResults razorResult = null; using (TextReader reader = new StringReader(entry.TemplateString)) { razorResult = new RazorTemplateEngine(host).GenerateCode(reader); } return(razorResult); }
public void RegisterTemplate <TModel>(string templateName, string templateString) { if (compiledTemplateAssembly != null) { throw new InvalidOperationException("May not register new templates after compiling."); } if (templateName == null) { throw new ArgumentNullException("templateName"); } if (templateString == null) { throw new ArgumentNullException("templateString"); } templateItems[TranslateKey(typeof(TModel), templateName)] = new RazorTemplateEntry() { ModelType = typeof(TModel), TemplateString = templateString, TemplateName = "Rzr" + Guid.NewGuid().ToString("N") }; }