How to create multiple output files from a single T4 template using Tangible Editor?

I remember I found an easier way to do it back in 2010, but now, after looking across the web for that method, I couldn't find it again. So, after some digging, I managed to find it in an old source code repository. Here's how I did it back then, without making use of any external file or dependency:

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

Please note that I don't know who the original author of this method is. If you happen to know who he or she is, please leave a comment.


<#@ template hostSpecific="true"#>

on top of .tt file solves everything.


This is the documentation from Tangible Engineering:

https://t4-editor.tangible-engineering.com/blog/how-to-generate-multiple-output-files-from-a-single-t4-template.html

It requires you to include and use the Template File Manager. The steps are briefly as follows:

  • Obtain the file manager from their free code gallery (https://t4-editor.tangible-engineering.com/Download_T4Editor_Plus_ModelingTools.html)
  • Include the file manager in the main template file:
    <#@ include file="TemplateFileManagerV2.1.ttinclude" #>
  • Instantiate a manager:
    <# var manager = TemplateFileManager.Create(this); #>
  • Use the manager to start a new file:
    <# manager.StartNewFile("Outputfile2.txt"); #>
    Note that this will end a previously started file before starting the next.
  • Generate template code as normal (will be generated in new file until another file is started or files are processed below)
  • Finalize all files (will end previously started file):
    <# manager.Process(); #>

Also, this method will automatically add the new files to the project.

Update -- pics included

Part 1: Generate multiple output files

Create your template

Create your template

Include reusable Template Manager from Template Gallery

Include reusable Template Manager from Template Gallery (pt. 1)

Include reusable Template Manager from Template Gallery (pt. 2)

Include reusable Template Manager from Template Gallery (pt. 3)

Test the output to multiple files

Test the output to multiple files (pt. 1)

Test the output to multiple files (pt. 2)

Part 2: Multiple output files in different projects

enter image description here