在前面的教程CodeSmith 使用教程(3): 自動產生Yii Framework ActiveRecord 我們使用了主,從模板來實現了從資料庫為Yii Framework產生多個表的ActiveRecord類定義,中CodeSmith項目中通過主模板和從模板的配合可以實現複雜的代碼產生過程,主模板和從模板的關係有點類似主程式和子函數的關係。使用主-從模板的基本步驟如下: 定義從模板,從模板可以定義屬性 定義主模板,中主模板中如果要使用從模板,首先需要在主模板中註冊從模板,主模板中也也可以定義屬性,主模板和從模板中的屬性可以通過定義“合并”模式構造最終模板所定義的屬性集合。 調用主模板,設定主模板和從模板所需的屬性產生所需代碼
註冊子模板
[csharp] view plain copy print ? <%@ Register Name="Header" Template="Header.cst" MergeProperties="True" ExcludeProperties="IncludeMeta" %>
<%@ Register Name="Header" Template="Header.cst" MergeProperties="True" ExcludeProperties="IncludeMeta" %>
Name:子模板在主模板中的類型名稱,在主要模板中可以通過該類型建立子模板的執行個體
Template: 子模板檔案名稱
MergeProperties: 是否需要把子模板中定義的屬性:“合并”到主模板中。預設為False
ExcludeProperties: 如果子模板的屬性合并到主模板中時需要排除的屬性列表,以逗號分隔。
子模板複製主模板中的屬性
MergeProperties=”True” 可以把從模板中的屬性合并到主模板中,如果從模板需要引用主模板的屬性,比如主模板中定義了伺服器位址,在多個子模板中都需要引用這個屬性,此時可以通過複製父模板屬性CopyPropertiesTo來實現: [csharp] view plain copy print ? // instantiate the sub-template Header header = this.Create<Header>(); // copy all properties with matching name and type to the sub-template instance this.CopyPropertiesTo(header);
// instantiate the sub-templateHeader header = this.Create<Header>();// copy all properties with matching name and type to the sub-template instancethis.CopyPropertiesTo(header);
CopyPropertiesTo方法比較主模板中定義的屬性和子模板中定義的屬性,如果發現從模板中定義的屬性和主模板中定義的屬性名稱類型相同(匹配)則把主模板中屬性值複製到子模板中。
設定子模板屬性
在主模板中要建立子模板的執行個體,可以直接通過Create方法 [csharp] view plain copy print ? // instantiate the sub-template Header header = this.Create<Header>(); // include the meta tag header.IncludeMeta = true;
// instantiate the sub-templateHeader header = this.Create<Header>();// include the meta tagheader.IncludeMeta = true;
Create中的Header為註冊子模板時Name來定義的類型,通過Create建立子模板的執行個體後,就直接可以通過該執行個體的屬性來訪問子模板中的屬性,比如上面代碼中IncludeMeta為子模板中定義的一個屬性。 從子模板輸出結果建立好子模板的執行個體,設定好子模板的屬性,在主模板中就可以讓子模板輸出結果,有幾種方法可以從子模板輸出內容。第一種是把子模板產生的結果直接插入到主模板中 [csharp] view plain copy print ? // instantiate the sub-template. Header header = this.Create<Header>(); // render the sub-template to the current output stream. header.Render(this.Response);
// instantiate the sub-template.Header header = this.Create<Header>();// render the sub-template to the current output stream.header.Render(this.Response);
第二種方法是把結果輸出到單獨的檔案中:
[csharp] view plain copy print ? // instantiate the sub-template. Header header = this.Create<Header>(); // render the sub-template to a separate file. header.RenderToFile("Somefile.txt");
// instantiate the sub-template.Header header = this.Create<Header>();// render the sub-template to a separate file.header.RenderToFile("Somefile.txt");
具體的例子可以參見 CodeSmith 使用教程(3): 自動產生Yii Framework ActiveRecord