Esempio n. 1
0
        private static GeneratorResults GenerateCode(RazorTemplateEntry entry, Type baseType)
        {
            var host = new RazorEngineHost(new CSharpRazorCodeLanguage());
            host.DefaultBaseClass = baseType.FullName;
            host.DefaultNamespace = "TeamConfig.Razor.Template";
            host.DefaultClassName = entry.TemplateName + "Template";
            host.NamespaceImports.Add("System");

            //filter out page directives and add them as namespace
            string templateString = entry.TemplateString;
            foreach (Match match in PageDirectivePattern.Matches(templateString))
            {
                string usedNamespace = match.Groups["Namespace"].Value;
                templateString = templateString.Replace(match.Value, string.Empty);
                if (usedNamespace.StartsWith("using"))
                {
                    host.NamespaceImports.Add(usedNamespace);
                }
            }

            GeneratorResults razorResult = null;

            using (TextReader reader = new StringReader(templateString))
            {
                var templateEngine = new RazorTemplateEngine(host);
                razorResult = templateEngine.GenerateCode(reader);
            }
            return razorResult;
        }
        public string RenderFromText(IDictionary<string, object> configValues, string templateString)
        {
            var props = new DynamicProperties();
            foreach (var configValue in configValues)
            {
                props.Add(configValue.Key,configValue.Value);
            }

            var entry = new RazorTemplateEntry() { TemplateString = templateString, TemplateName = "Rzr" + Guid.NewGuid().ToString("N") };
            var compiledTemplateAssembly = Compiler.Compile(entry, typeof(RazorTemplateBase));

            var template = (RazorTemplateBase)compiledTemplateAssembly.CreateInstance("TeamConfig.Razor.Template." + entry.TemplateName + "Template");
            template.Model = props;
            template.Execute();
            var output = template.Buffer.ToString();
            template.Buffer.Clear();
            return output;
        }
Esempio n. 3
0
 public static Assembly Compile(RazorTemplateEntry razorTemplateEntry, Type baseType)
 {
     return Compile(new[] { razorTemplateEntry }, baseType);
 }