Dumi
Dumi

Reputation: 1434

T4 template generated files are not nested under .tt file

Since I wanted a generate multiple files using T4 templates, I have added a T4 template file to a Class Library (.NET Core) project (.net Core 2.1).

enter image description here

I added following code to T4 template.

<#@ 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);
}
#>

As expected, this created 5 text files.

enter image description here

However, the files created from the template are not nested to the "Generated.Files.tt" file. How do we nested these files under "Generated.Files.tt" so if I expand the tt file, I would like to see the generated files.

Upvotes: 1

Views: 1763

Answers (1)

Tim Maes
Tim Maes

Reputation: 612

this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);is what removes the output to the childnode. In that template manually create the files and write output to it in your SaveOutput method.

Just remove that method and output is automatically generated in a childnode.

Example:

<#@ 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 #>
<#
}
#>

Just removing this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length); will cause the template to generate a childnode, but you're still writing to files yourself then.

Here is a basic tutorial with some explanation.

Upvotes: 1

Related Questions