T4 模板入門


T4,即4個T開頭的英文字母組合:Text Template Transformation Toolkit。T4(Text Template Transformation Toolkit)是微軟官方在VisualStudio 2008中開始使用的代碼生成引擎。簡單的說就是可以根據模板生成你想要的文件,可以使類文件,文本文件,HTML等等。

VS本身只提供一套基於T4引擎的代碼生成的執行環境,由下面程序集構成:

Microsoft.VisualStudio.TextTemplating.10.0.dll

Microsoft.VisualStudio.TextTemplating.Interfaces.10.0.dll

Microsoft.VisualStudio.TextTemplating.Modeling.10.0.dll

Microsoft.VisualStudio.TextTemplating.VSHost.10.0.dll

 

T4模板編輯器插件:

vs默認編輯器無高亮,無提示。T4編輯器有多款,這只是其中一個。

T4的編輯工具下載地址http://t4-editor.tangible-engineering.com/Download_T4Editor_Plus_ModelingTools.html

 

T4基本語法:

  T4語法主要包括三類:

  1. 指令塊 - 向文本模板化引擎提供關於如何生成轉換代碼和輸出文件的一般指令。
    #@ output extension=".txt" #>  
  2. 文本塊 - 直接復制到輸出的內容。
    <#@ output extension=".txt" #>  
    Hello 
  3. 控制塊 - 向文本插入可變值並控制文本的條件或重復部件的程序代碼,不能在控制塊中嵌套控制塊。
    1. 標准控制塊。
      <#  
          for(int i = 0; i < 4; i++)  
          {  
      #>  
      Hello!  
      <#  
          }   
      #> 
    2. 表達式控制塊。
      <#= 2 + 3 #>  
    3. 類功能控制塊。
    4. <#@ output extension=".txt" #>  
      Squares:  
      <#  
          for(int i = 0; i < 4; i++)  
          {  
      #>  
          The square of <#= i #> is <#= Square(i+1) #>.  
      <#  
          }   
      #>  
      That is the end of the list.  
      <#+   // Start of class feature block  類功能控制塊以 <#+ ... #> 符號分隔。
      private int Square(int i)  
      {  
          return i*i;  
      }  
      #>  
    5. List of Squares:  
      <#  
         for(int i = 0; i < 4; i++)  
         {  WriteSquareLine(i); }  
      #>  
      End of list.  
      <#+   // Class feature block  類功能塊包含文本塊
      private void WriteSquareLine(int i)  
      {  
      #>  
         The square of <#= i #> is <#= i*i #>.  
      <#+     
      }  
      #> 

 指令:

<#@ DirectiveName [AttributeName = "AttributeValue"] ... #>  
  1. T4 模板指令
    <#@ template [language="VB"] [compilerOptions="options"] [culture="code"] [debug="true"] [hostspecific="true"] [inherits="templateBaseClass"] [visibility="internal"] [linePragmas="false"] #>  
  2. T4 參數指令
    <#@ parameter type="Full.TypeName" name="ParameterName" #>
  3. T4 輸出指令
    <#@ output extension=".fileNameExtension" [encoding="encoding"] #> 
  4. T4 程序集指令
    <#@ assembly name="[assembly strong name|assembly file name]" #>  
  5. T4 導入指令
    <#@ import namespace="namespace" #>  
  6. T4 包含指令
    <#@ include file="filePath" #>  
  7. T4 CleanUpBehavior 指令
    <#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #>  

 

 


  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM