T4模板简单了解

T4模板基础

T4即为Text Template Transformation Toolkit,一种可以由自己去自定义规则的代码生成器。根据业务模型可生成任何形式的文本文件或供程序调用的字符串

在VS中T4模板是没有智能提示和颜色标注的,可以安装官方推荐插件:tangibleT4EditorPlusModellingTools

T4模板有两种类型:

  • 设计时模板(文本模板)

  当需求变化时,可以根据业务需求调整模型(输入),按照指定规则将“模型”生成任何类型的“文本文件”,例如:网页、资源文件或任何语言的程序源代码。

  • 运行时模板(已预处理的文本模板)   

  可以根据业务需求调整模型(输入),在运行时按照指定规则将“模型”生成为“文本字符串”。 运行时文本模板中不需要输出指令

三种基本结构分为指令块、文本块、控制块。

指令块

 向文本模板化引擎提供关于如何生成转换代码和输出文件的一般指令,简单来说就是告诉编译器是如何处理

 格式:<#@ 指令 属性=“值” #>

 有6个指令

  • <#@ template #>
  • <#@ parameter#>
  • <#@ assembly #>
  • <#@ import #>
  • <#@ include #>
  • <#@ output #>

 如:

<#@ include file="..\MultipleOutputHelper.ttinclude" #> //包含另一模板文件
<#@ assembly name="$(ProjectDir)MySql.Data.dll" #> //MySql.Data.dll放在项目根目录

文本块 

 就是直接输出的内容,文本块没有特殊格式

控制块

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

  • <# 标准控制块 #>         可以包含语句。
  • <#= 表达式控制块 #>        可以包含表达式。 如: <#= 变量 #>
  • <#+ 类特征控制块 #>        可以包含方法、字段和属性,定义类,但不包含任何文本块和其他控制块,通常用于编写帮助类函数

 一个T4如何生成多个文件

正常情况下,一个T4只能指定一个输出文件

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

生成多个文件步骤如下:

  • 创建一个【 MultipleOutputHelper.ttinclude 】模板,放入自己的项目,代码内容如下
<#@ assembly name="System.Core"#>
<#@ assembly name="System.Data.Linq"#>
<#@ assembly name="EnvDTE"#>
<#@ assembly name="System.Xml"#>
<#@ assembly name="System.Xml.Linq"#>
<#@ import namespace="System.Collections.Generic"#>
<#@ import namespace="System.IO"#>
<#@ import namespace="System.Text"#>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating"#>
<#+ // https://raw.github.com/damieng/DamienGKit // http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited // Manager class records the various blocks so it can split them up class Manager { private class Block { public String Name; public int Start, Length; public bool IncludeInDefault; } private Block currentBlock; private readonly List<Block> files = new List<Block>(); private readonly Block footer = new Block(); private readonly Block header = new Block(); private readonly ITextTemplatingEngineHost host; private readonly StringBuilder template; protected readonly List<String> generatedFileNames = new List<String>(); public static Manager Create(ITextTemplatingEngineHost host, StringBuilder template) { return (host is IServiceProvider) ? new VSManager(host, template) : new Manager(host, template); } public void StartNewFile(String name) { if (name == null) throw new ArgumentNullException("name"); CurrentBlock = new Block { Name = name }; } public void StartFooter(bool includeInDefault = true) { CurrentBlock = footer; footer.IncludeInDefault = includeInDefault; } public void StartHeader(bool includeInDefault = true) { CurrentBlock = header; header.IncludeInDefault = includeInDefault; } public void EndBlock() { if (CurrentBlock == null) return; CurrentBlock.Length = template.Length - CurrentBlock.Start; if (CurrentBlock != header && CurrentBlock != footer) files.Add(CurrentBlock); currentBlock = null; } public virtual void Process(bool split, bool sync = true) { if (split) { EndBlock(); String headerText = template.ToString(header.Start, header.Length); String footerText = template.ToString(footer.Start, footer.Length); String outputPath = Path.GetDirectoryName(host.TemplateFile); files.Reverse(); if (!footer.IncludeInDefault) template.Remove(footer.Start, footer.Length); foreach(Block block in files) { String fileName = Path.Combine(outputPath, block.Name); String content = headerText + template.ToString(block.Start, block.Length) + footerText; generatedFileNames.Add(fileName); CreateFile(fileName, content); template.Remove(block.Start, block.Length); } if (!header.IncludeInDefault) template.Remove(header.Start, header.Length); } } protected virtual void CreateFile(String fileName, String content) { if (IsFileContentDifferent(fileName, content)) File.WriteAllText(fileName, content); } public virtual String GetCustomToolNamespace(String fileName) { return null; } public virtual String DefaultProjectNamespace { get { return null; } } protected bool IsFileContentDifferent(String fileName, String newContent) { return !(File.Exists(fileName) && File.ReadAllText(fileName) == newContent); } private Manager(ITextTemplatingEngineHost host, StringBuilder template) { this.host = host; this.template = template; } private Block CurrentBlock { get { return currentBlock; } set { if (CurrentBlock != null) EndBlock(); if (value != null) value.Start = template.Length; currentBlock = value; } } private class VSManager: Manager { private readonly EnvDTE.ProjectItem templateProjectItem; private readonly EnvDTE.DTE dte; private readonly Action<String> checkOutAction; private readonly Action<List<String>> projectSyncAction; public override String DefaultProjectNamespace { get { return templateProjectItem.ContainingProject.Properties.Item("DefaultNamespace").Value.ToString(); } } public override String GetCustomToolNamespace(string fileName) { return dte.Solution.FindProjectItem(fileName).Properties.Item("CustomToolNamespace").Value.ToString(); } public override void Process(bool split, bool sync) { if (templateProjectItem.ProjectItems == null) return; base.Process(split, sync); if (sync) projectSyncAction.EndInvoke(projectSyncAction.BeginInvoke(generatedFileNames, null, null)); } protected override void CreateFile(String fileName, String content) { if (IsFileContentDifferent(fileName, content)) { CheckoutFileIfRequired(fileName); File.WriteAllText(fileName, content); } } internal VSManager(ITextTemplatingEngineHost host, StringBuilder template) : base(host, template) { var hostServiceProvider = (IServiceProvider)host; if (hostServiceProvider == null) throw new ArgumentNullException("Could not obtain IServiceProvider"); dte = (EnvDTE.DTE) hostServiceProvider.GetService(typeof(EnvDTE.DTE)); if (dte == null) throw new ArgumentNullException("Could not obtain DTE from host"); templateProjectItem = dte.Solution.FindProjectItem(host.TemplateFile); checkOutAction = fileName => dte.SourceControl.CheckOutItem(fileName); projectSyncAction = keepFileNames => ProjectSync(templateProjectItem, keepFileNames); } private static void ProjectSync(EnvDTE.ProjectItem templateProjectItem, List<String> keepFileNames) { var keepFileNameSet = new HashSet<String>(keepFileNames); var projectFiles = new Dictionary<String, EnvDTE.ProjectItem>(); var originalFilePrefix = Path.GetFileNameWithoutExtension(templateProjectItem.FileNames[0]) + "."; foreach (EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems) projectFiles.Add(projectItem.FileNames[0], projectItem); // Remove unused items from the project foreach (var pair in projectFiles) if (!keepFileNames.Contains(pair.Key) && !(Path.GetFileNameWithoutExtension(pair.Key) + ".").StartsWith(originalFilePrefix)) pair.Value.Delete(); // Add missing files to the project foreach(String fileName in keepFileNameSet) if (!projectFiles.ContainsKey(fileName)) templateProjectItem.ProjectItems.AddFromFile(fileName); } private void CheckoutFileIfRequired(String fileName) { var sc = dte.SourceControl; if (sc != null && sc.IsItemUnderSCC(fileName) && !sc.IsItemCheckedOut(fileName)) checkOutAction.EndInvoke(checkOutAction.BeginInvoke(fileName, null, null)); } } } #>
  • 在自己的T4模板包含引用MultipleOutputHelper.ttinclude,并进行创建对象
<#@ template language="C#" hostspecific="True"#>  
<#@ include file="MultipleOutputHelper.ttinclude"#> 
<#  var manager = Manager.Create(Host, GenerationEnvironment); #>  
  • 【1.txt 】为要输出文件的名称(循环就是多个文件)
<# manager.StartNewFile("1.txt"); #>  
 //要输入的内容
<# manager.EndBlock(); #>  
  • 可以为所有的输出文件设置 同样的头部或尾部,
<# manager.StartHeader(); #>
//大家共有的头部信息
<# manager.EndBlock(); #>
<# manager.StartFooter(); #>
// 大家共有的尾部信息
<# manager.EndBlock(); #>
  • 最后确定执行输出多个文件
<# manager.Process(true); #> 

 

posted @ 2018-06-14 23:49  【可乐不加冰】  阅读(3800)  评论(3编辑  收藏  举报