CodeSmith用子模版的RenderToFile输出到指定文件
CodeSmith是一款不错的.Net开发辅助工具,可以使工作效率得到很大提高。最近用它做了一项目,其中要自动保存多个文件。上网查了查,能查到的都是用继承Inherits="OutputFileCodeTemplate" 方法来实现,个人觉得这方法过于麻烦。后来查了查CodeSmith 4.1的联机帮助,里面讲得很清楚,用子模版的RenderToFile就可以了,原文如下:
以下是我写的Demo,很简单吧:
This technique is useful for generating multiple identical copies of the same file. When you need to generate multiple different files as part of a single code-generation process, you should use one sub-template for each file. Call the sub-templates from a master template and use the RenderToFile method to output each sub-template. |
1public void RenderMyAspxCs(TableSchema table,string strTableName,string nameSpaceStr)
2{
3 CodeTemplate subTemplate=null;
4 subTemplate=CreateSubTemplate(@"..\Web.UI\MyAspx.cs.cst"); //创建template
5 if(subTemplate!=null)
6 {
7 subTemplate.SetProperty("CurTable", table);
8 subTemplate.SetProperty("NameSpaces", "CommunityOA.Web.Module.OA."+nameSpaceStr);
9 subTemplate.SetProperty("EntityName", strTableName);
10 subTemplate.SetProperty("CodeEntity",strTableName);
11
13 subTemplate.RenderToFile(FoldName+"\\"+nameSpaceStr+"\\My.Aspx.cs",true); //输出到文件
14 // Response.WriteLine(FoldName+"\\"+nameSpaceStr+"\\Manager.Aspx.cs"); //得示信息
15 }
16}
17
18public CodeTemplate CreateSubTemplate(string SubTempName)
19{
20 CodeTemplate _SubTemplate=null; //定义子模块
21 CodeTemplateCompiler compiler = new CodeTemplateCompiler(this.CodeTemplateInfo.DirectoryName + SubTempName);
22 compiler.Compile();
23
24 if (compiler.Errors.Count == 0)
25 {
26 _SubTemplate = compiler.CreateInstance();
27 }
28 else
29 {
30 for (int i = 0; i < compiler.Errors.Count; i++)
31 {
32 Response.WriteLine(compiler.Errors[ i].ToString());
33 }
34 }
35
36 return _SubTemplate;
37}
38
2{
3 CodeTemplate subTemplate=null;
4 subTemplate=CreateSubTemplate(@"..\Web.UI\MyAspx.cs.cst"); //创建template
5 if(subTemplate!=null)
6 {
7 subTemplate.SetProperty("CurTable", table);
8 subTemplate.SetProperty("NameSpaces", "CommunityOA.Web.Module.OA."+nameSpaceStr);
9 subTemplate.SetProperty("EntityName", strTableName);
10 subTemplate.SetProperty("CodeEntity",strTableName);
11
13 subTemplate.RenderToFile(FoldName+"\\"+nameSpaceStr+"\\My.Aspx.cs",true); //输出到文件
14 // Response.WriteLine(FoldName+"\\"+nameSpaceStr+"\\Manager.Aspx.cs"); //得示信息
15 }
16}
17
18public CodeTemplate CreateSubTemplate(string SubTempName)
19{
20 CodeTemplate _SubTemplate=null; //定义子模块
21 CodeTemplateCompiler compiler = new CodeTemplateCompiler(this.CodeTemplateInfo.DirectoryName + SubTempName);
22 compiler.Compile();
23
24 if (compiler.Errors.Count == 0)
25 {
26 _SubTemplate = compiler.CreateInstance();
27 }
28 else
29 {
30 for (int i = 0; i < compiler.Errors.Count; i++)
31 {
32 Response.WriteLine(compiler.Errors[ i].ToString());
33 }
34 }
35
36 return _SubTemplate;
37}
38