tags:

views:

78

answers:

2

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? :)

A: 

Templates have the TransformText() method which you can call to programatically generate your file.

 Template webTemplate = // programmatically fetch template in defined in web.tt above.
 webTemplate.EnvironmentName = environmentName;
 string output = webTemplate.TransformText();
Kirk Woll
I find that redefining my template as a class and overriding TransformText() to contain the full content of my template is a bit cumbersome. Isn't there some way that I can write a "plain" template and access it by name or type from another template?
urig
+1  A: 

The following article shows how to do exactly that for a T-SQL stored procedure.

http://www.olegsych.com/2008/09/t4-tutorial-creating-reusable-code-generation-templates/

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.

Hope this helps,

Oleg

Oleg Sych
Hi Oleg. I've already read your blog post and many others that you've written on T4. You're the man! So the only approach is to embed the contents of my template inside the TransformText() method of a class that derives from Template?
urig