T4 模板

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语法主要包括三类:

指令块 - 向文本模板化引擎提供关于如何生成转换代码和输出文件的一般指令。

#@ output extension=".txt" #>  

1.文本块 - 直接复制到输出的内容。

<#@ output extension=".txt" #>  
Hello 

2.控制块 - 向文本插入可变值并控制文本的条件或重复部件的程序代码,不能在控制块中嵌套控制块。

3.标准控制块。

<#  
    for(int i = 0; i < 4; i++)  
    {  
#>  
Hello!  
<#  
    }   
#> 

4.表达式控制块。

<#= 2 + 3 #>  

5.类功能控制块。

<#@ 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;  
}  
#>  
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"] ... #>  

T4 模板指令

<#@ template [language="VB"] [compilerOptions="options"] [culture="code"] [debug="true"] [hostspecific="true"] [inherits="templateBaseClass"] [visibility="internal"] [linePragmas="false"] #>  

T4 参数指令

<#@ parameter type="Full.TypeName" name="ParameterName" #>

T4 输出指令

<#@ output extension=".fileNameExtension" [encoding="encoding"] #> 

T4 程序集指令

<#@ assembly name="[assembly strong name|assembly file name]" #>  

T4 导入指令

<#@ import namespace="namespace" #>  

T4 包含指令

<#@ include file="filePath" #>  

T4 CleanUpBehavior 指令

<#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #>  
原文地址:https://www.cnblogs.com/geduocoding/p/9638411.html