コード例 #1
0
        /// <summary>
        /// Compiles the string cshtml template into a cs string
        /// </summary>
        /// <param name="className">The name of the compiled class.</param>
        /// <param name="template">The template to compile.</param>
        /// <param name="modelType">[Optional] The model type.</param>
        /// <param name="baseTypeName">[Optional] Base type for the template. To be used if the model type is
        /// in an unreferenced assembly.</param>
        /// <returns>The results of compilation.</returns>
        public string GetCode(string className, string template, Type modelType = null, string baseTypeName = null, string outputNamespace = null)
        {
            if (className == null)
            {
                className = Regex.Replace(Guid.NewGuid().ToString("N"), @"[^A-Za-z]*", "");
            }
            var service = languageProvider.CreateLanguageService();
            var codeDom = languageProvider.CreateCodeDomProvider();
            var host    = new RazorEngineHost(service);

            host.GeneratedClassContext = new GeneratedClassContext("Execute", "Write", "WriteLiteral", "WriteTo", "WriteLiteralTo", "RazorEngine.Templating.TemplateWriter");

            var generator  = service.CreateCodeGenerator(className, outputNamespace ?? "RazorEngine.Dynamic", null, host);
            var codeParser = service.CreateCodeParser();

            var parser = new RazorParser(codeParser, markupParser);

            AddNamespaceImports(generator.GeneratedNamespace);
            string baseType = baseTypeName;

            if (baseTypeName == null)
            {
                baseType = GetBaseTypeDeclaration(languageProvider, modelType, templateBaseType);
            }

            generator.GeneratedClass.BaseTypes.Add(baseType);

            if ((modelType != null) && IsAnonymousType(modelType))
            {
                generator.GeneratedClass.CustomAttributes.Add(
                    new CodeAttributeDeclaration(
                        new CodeTypeReference(typeof(HasDynamicModelAttribute))));
            }

            ParseTemplate(template, parser, generator);

            var builder = new StringBuilder();

            GenerateCode(codeDom, generator, builder);

            return(builder.ToString());
        }