CodeSmith实用技巧(九):重载Render方法来控制输出
在CodeSmith中,CodeTemplate.Render方法是在模版执行完成进行模版输出时执行,你可以通过重载CodeTemplate.Render方法来修改CodeSmith输出时的事件处理。例如:你可以修改模版输出时的方式来代替现在默认的方式,下面这段代码展示了在保持CodeSmith默认的窗口显示的同时,把结果输出到两个不同的文件。
注意不能忘了base.Render(writer);这句话,否则你将不能获得默认的输出。当重载CodeTemplate.Render方法时,你也可
以访问TextWriter,也就是说你也可以直接添加其它的附属信息到模版输出的内容中。
1<%@ CodeTemplate Language="C#" TargetLanguage="Text" Description="AddTextWriter Demonstration." %>
2<%@ Import Namespace="System.IO" %>
3This template demonstrates using the AddTextWriter method
4to output the template results to multiple locations concurrently.
5<script runat="template">
6public override void Render(TextWriter writer)
7{
8 StreamWriter fileWriter1 = new StreamWriter(@"C:\test1.txt", true);
9 this.Response.AddTextWriter(fileWriter1);
10
11 StreamWriter fileWriter2 = new StreamWriter(@"C:\test2.txt", true);
12 this.Response.AddTextWriter(fileWriter2);
13
14 base.Render(writer);
15
16 fileWriter1.Close();
17 fileWriter2.Close();
18}
19</script>
2<%@ Import Namespace="System.IO" %>
3This template demonstrates using the AddTextWriter method
4to output the template results to multiple locations concurrently.
5<script runat="template">
6public override void Render(TextWriter writer)
7{
8 StreamWriter fileWriter1 = new StreamWriter(@"C:\test1.txt", true);
9 this.Response.AddTextWriter(fileWriter1);
10
11 StreamWriter fileWriter2 = new StreamWriter(@"C:\test2.txt", true);
12 this.Response.AddTextWriter(fileWriter2);
13
14 base.Render(writer);
15
16 fileWriter1.Close();
17 fileWriter2.Close();
18}
19</script>
以访问TextWriter,也就是说你也可以直接添加其它的附属信息到模版输出的内容中。