T4即爲Text Template Transformation Toolkit,一種能夠由本身去自定義規則的代碼生成器。根據業務模型可生成任何形式的文本文件或供程序調用的字符串git
在VS中T4模板是沒有智能提示和顏色標註的,能夠安裝官方推薦插件:tangibleT4EditorPlusModellingToolsgithub
T4模板有兩種類型:ide
當需求變化時,能夠根據業務需求調整模型(輸入),按照指定規則將「模型」生成任何類型的「文本文件」,例如:網頁、資源文件或任何語言的程序源代碼。函數
能夠根據業務需求調整模型(輸入),在運行時按照指定規則將「模型」生成爲「文本字符串」。 運行時文本模板中不須要輸出指令ui
三種基本結構分爲:指令塊、文本塊、控制塊。this
向文本模板化引擎提供關於如何生成轉換代碼和輸出文件的通常指令,簡單來講就是告訴編譯器是如何處理spa
格式:<#@ 指令 屬性=「值」 #>插件
有6個指令設計
如:code
<#@ include file="..\MultipleOutputHelper.ttinclude" #> //包含另外一模板文件 <#@ assembly name="$(ProjectDir)MySql.Data.dll" #> //MySql.Data.dll放在項目根目錄
就是直接輸出的內容,文本塊沒有特殊格式
向文本插入可變值並控制文本的條件或重複部件的程序代碼,不能在控制塊中嵌套控制塊
正常狀況下,一個T4只能指定一個輸出文件
<#@ output extension=".txt"#>
生成多個文件步驟以下:
<#@ 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)); } } } #>
<#@ template language="C#" hostspecific="True"#> <#@ include file="MultipleOutputHelper.ttinclude"#> <# var manager = Manager.Create(Host, GenerationEnvironment); #>
<# manager.StartNewFile("1.txt"); #> //要輸入的內容 <# manager.EndBlock(); #>
<# manager.StartHeader(); #> //你們共有的頭部信息 <# manager.EndBlock(); #>
<# manager.StartFooter(); #> // 你們共有的尾部信息 <# manager.EndBlock(); #>
<# manager.Process(true); #>