【问题标题】:T4 template generated files are not nested under .tt fileT4 模板生成的文件没有嵌套在 .tt 文件下
【发布时间】:2019-06-16 14:48:25
【问题描述】:

由于我想使用 T4 模板生成多个文件,因此我已将 T4 模板文件添加到类库 (.NET Core) 项目 (.net Core 2.1)。

我在 T4 模板中添加了以下代码。

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ output extension=".txt" #>
<#
for (Int32 i = 0; i < 5; ++i) {
#>
Content <#= i #>
<#
  // End of file.
  SaveOutput("Content" + i.ToString() + ".txt");
}
#>
<#+
private void SaveOutput(string outputFileName) {
  string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
  string outputFilePath = Path.Combine(templateDirectory, outputFileName);
  File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); 
  this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
}
#>

正如预期的那样,这创建了 5 个文本文件。

但是,从模板创建的文件不会嵌套到“Generated.Files.tt”文件中。我们如何将这些文件嵌套在“Generated.Files.tt”下,所以如果我展开 tt 文件,我想查看生成的文件。

【问题讨论】:

    标签: templates .net-core nested t4 auto-generate


    【解决方案1】:

    this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);是删除子节点的输出。在该模板中手动创建文件并在 SaveOutput 方法中将输出写入其中。

    只需删除该方法,输出就会在子节点中自动生成。

    例子:

    <#@ template debug="false" hostspecific="true" language="C#" #>
    <#@ assembly name="System.Core" #>
    <#@ import namespace="System" #>
    <#@ import namespace="System.IO" #>
    <#@ output extension=".txt" #>
    <#
    for (Int32 i = 0; i < 5; ++i) {
    #>
    Content <#= i #>
    <#
    }
    #>
    

    仅删除 this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length); 会导致模板生成子节点,但您仍然要自己写入文件。

    Here 是一个带有一些解释的基础教程。

    【讨论】:

      猜你喜欢
      • 2011-05-10
      • 2012-08-07
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      相关资源
      最近更新 更多