Search code examples
t4

Access T4 template programmatically


I've written a simple T4 template (call it "web.tt) to generate a web.config file. Here's the gist of it:

<#@ template debug="true" language="C#" hostSpecific="true" #>
<#@ output extension=".config" #>
<?xml version="1.0" encoding="UTF-8"?>

<configuration>
    <!-- yadda yadda yadda -->
</configuration>

Can I access this template programmatically from a T4 Toolbox Generator class? I need something like:

<#@ include file="web.tt" #>
<#+
// <copyright file="Generator1.tt" company="Microsoft">
//  Copyright © Microsoft. All Rights Reserved.
// </copyright>

public class Generator1 : Generator
{
    protected override void RunCore()
    {
        string[] environmentNames = new string[] { "env1", "env2", "env3" };
        foreach (string environmentName in environmentNames)
        {
            Template webTemplate = // programmatically fetch template in defined in web.tt above.
            webTemplate.EnvironmentName = environmentName;
            webTemplate.RenderToFile(environmentName);
        }
    }
}
#>

Can you point me in the right direction? :)


Solution

  • This article shows how to do exactly that for a T-SQL stored procedure.

    In other words, you would define a Template class in your web.tt and create a new instance of it in the RunCore of your generator.