Tim Maes
Tim Maes

Reputation: 612

Write T4 generated code to separate output files

I am creating a .tt file that transforms text into model classes, to practice.

A .cs file is generated that with all models, but I would like each model to be saved in its own .cs file in a different folder.

What would be the best approach to achieve this?

Upvotes: 3

Views: 2885

Answers (1)

Risto M
Risto M

Reputation: 2999

Here is simple example how you can output multiple files from single T4 template.

Using SaveOutput-method output files (Content1.txt,Content2.txt..) are created to same folder than .tt-file, with SaveOutputToSubFolder output files goes to separate folders (1\Content1.txt, 2\Content2.txt..)

<#@ 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 < 10; ++i) {
#>
File Content <#= i #>
<#

  SaveOutput("Content" + i.ToString() + ".txt");
  //Uncomment following to write to separate folder 1,2,3
  //SaveOutputToSubFolder(i.ToString(),"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.Clear();
}
private void SaveOutputToSubFolder(string folderName, string outputFileName) {
  string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
  string newDirectoryName = Path.Combine(templateDirectory,folderName);
  if(!Directory.Exists(newDirectoryName))
    Directory.CreateDirectory(newDirectoryName);
  string outputFilePath = Path.Combine(newDirectoryName, outputFileName);
  File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); 
  this.GenerationEnvironment.Clear();
}
#>

Upvotes: 6

Related Questions