Example #1
0
        private static async void Method02()
        {
            // Compile the template into an in-memory assembly
            TemplateDescriptor template = Razor.Compile("<p>Hello, @Model.Name!</p>");

            // Render the template to string
            var output = await template.RenderAsync(new CodeModule { Name = "World" });
        }
Example #2
0
        /// <summary>
        /// 生成代码
        /// </summary>
        /// <param name="template">代码配置</param>
        /// <param name="model">代码数据模型</param>
        /// <param name="fileName">代码输出文件</param>
        /// <returns></returns>
        protected virtual async Task <CodeFile> GenerateCodeCore(CodeTemplate template, object model, string fileName)
        {
            StringBuilder sb = new StringBuilder();

            await using TextWriter writer = new StringWriter(sb);
            if (template.TemplateFile == "内置")
            {
                Type      innerTemplateType = template.GetInnerTemplateType();
                ITemplate template2         = (ITemplate)(Activator.CreateInstance(innerTemplateType)
                                                          ?? throw new OsharpException($"代码配置“{template.Name}”的模板类型实例化失败"));
                template2.Model  = model;
                template2.Output = writer;
                await template2.ExecuteAsync();
            }
            else
            {
                if (template.TemplateFile == null || !File.Exists(template.TemplateFile))
                {
                    throw new OsharpException($"代码配置“{template.Name}”的模板文件“{template.TemplateFile}”不存在");
                }

                string templateSource = await File.ReadAllTextAsync(template.TemplateFile);

                TemplateDescriptor descriptor = Razor.Compile(templateSource);
                await descriptor.RenderAsync(writer, model);
            }

            string codeSource = sb.ToString();

            CodeFile codeFile = new CodeFile()
            {
                Template   = template,
                SourceCode = codeSource,
                FileName   = fileName
            };

            return(codeFile);
        }