How to create a simple T4 template


This article demonstrates how to create and use a simple T4 template to generate C# code in Visual Studio without building a DSL or a Guidance package.

Example

In order to follow the walkthrough, you will need Visual Studio 2005 Standard (or higher) Edition and DSL Tools installed on your computer. You may also want to install T4 Editor by Tangible Engineering, which adds IntelliSense and syntax highlighting to Visual Studio text editor for T4 templates.

1. In Visual Studio, create a new C# Console Application project.

2. Add a new text file called MyPot.tt to the project.

If you select MyPot.tt in Solution Explorer and open Properties window, you will notice that Visual Studio recognized the extension, assigned a Custom Tool called TextTemplateFileGenerator to MyPot.tt and generated an empty MyPot.cs file under it.

3. Add the following text to MyPot.tt.

<#@ template language=C##>
// <autogenerated>
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
// </autogenerated>
using System;   

public class <#= this.ClassName #>
{
   public static void HelloPot()
   {
      Console.WriteLine(”Hello, POT”);
   }
}
<#+
string ClassName = “MyClass”;
#>

This template will generate a class with the name specified by the ClassName field. When you save MyPot.tt, Visual Studio will automatically regenerate MyPot.cs and you should see something like this:

// <autogenerated>
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
// </autogenerated>
using System;  

public class MyClass
{
    public static void HelloPot()
    {
        Console.WriteLine(“Hello, POT”);
    }
}

Visual Studio will regenerate MyPot.cs every time you make changes and save MyPot.tt. You can also regenerate MyPot.cs by right-clicking MyPot.tt in Solution Explorer and selecting “Run Custom Tool” from the context menu. Continue modifying MyPot.tt and checking its output in MyPot.cs until the template is finished.

4. Add a new text file called TestClass.tt to the project and enter the following text in it.

<#
    this.ClassName = “TestClass”;
#>
<#@ include file=MyPot.tt#>

This file includes MyPot.tt, and overrides template parameters to generate the actual source code our sample application will use. As soon as you save TestClass.tt, Visual Studio will generate TestClass.cs based on the template in MyPot.tt and the parameters (ClassName) specified in TestClass.tt. Now you can start using TestClass just like any other class in your program.

You can generate as many actual classes based on a single template as you need. At some point you will probably want to clear Custom Tool property for MyPot.tt and remove MyPot.cs from the project to prevent template test code from being compiled. If you change MyPot.tt after generating TestClass.cs, you will need to right-click TestClass.tt in Solution Explorer and select “Run Custom Tool” to regenerate TestClass.cs. You can also click “Transform All Templates” in the Solution Explorer toolbar.

Conclusion

T4 allows you to quickly generate source code. Its similarity with ASP.NET-like templates and Visual Studio studio makes it practical for code generation in application development projects.

About T4

T4 (Text Template Transformation Toolkit) is a template-based code generation engine. It is available in Visual Studio 2008 and as a download in DSL and GAT toolkits for Visual Studio 2005. T4 engine allows you to use ASP.NET-like template syntax to generate C#, T-SQL, XML or any other text files.

For more information about T4, check out my previous article.

Download

T4 templates and source code used in this article are available for download here.


Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

OK I’ll bite - why did you call it Hello POT?

I was trying to be funny.

Great article Oleg, thanks.

T4 will be great for generating Data access layer code. Should save me tedious typing.

Have created T4 templates for data access layer generation before? Could you send me a sample if you have? I would like pass in the name of a table and have T4 generate code for an insert block of code.

-Joseph

[…] How to create a simple T4 template […]

[…] Download the templates from Tangible, there is a gratis version. Use the Simple and the Advanced templates from Tangible. Read Oleg’s article. […]

When I copied and pasted the MyPott.tt code into MyPot.tt and tried to save it, it gave me an error “A directive was specified in the wrong format. The transformation will not be run. Please specify the directive in the format “. Is it because of the version of VS2008?

The problem is quote character [”]. Just replace with the correct one.

Thanks for this introduction.
> In order to follow the walkthrough, you will need Visual Studio 2005 Standard (or higher) Edition
It actually works for me when using Visual Studio 2010 Express.

Dude in your code snippets your double quote doesn’t work when pasted into a T4 template.

Yeah, unfortunately. I’ll try to get this fixed after migrating to a new CMS.