T4: Text Template Transformation Toolkit


Text Template Transformation Toolkit (T4) is a template-based code generation engine. It is included with Visual Studio 2008 and available as a download for Visual Studio 2005 in DSL and GAT toolkits. You can use T4 templates to generate Visual Basic, C#, T-SQL, XML or any other text files.

Syntax

T4 templates have ASP.NET-like syntax and consist of processing directives, text blocks and code blocks.

<#@ template language=C##>
Hello
<# Write(”World!”) #>

Processing directives provide template compilation and processing options. In the example above, <#@ template #> directive specifies that code blocks of this template are written in C#.

Text blocks are copied to the output “as is”. In the example above, Hello is a text block.

Code blocks contain Visual Basic or C# code that can manipulate text blocks or generate template output directly. In the example above, the code block calls Write method which writes “World!” to the output file. Code blocks can use any available .NET APIs. For example, a template can use SMO to generate CRUD stored procedures for a table in a SQL Server database.

How it works

T4 engine performs two steps to generate output from a template.

T4 Template Transformation Process

During the first step, T4 engine “compiles” the template: it parses the processing instructions, text and code blocks, generates a concrete TextTransformation class, and compiles it into a .NET assembly. During the second step, T4 engine creates an instance of the GeneratedTextTransformation class, calls its TransformText method and saves the string it returns to the output file.

Tutorial

This series of articles introduces code generation with C# and Text Templates in Visual Studio; explains how to create reusable templates and combine them in complex code generators.

Tools

Here are the tools you will be using when working with T4 text templates.

Visual Studio Custom Tool

T4 engine is integrated as a custom tool into Visual Studio 2008. When you add a text file with .tt extension to your project, Visual Studio assigns TextTemplatingFileGenerator as a custom tool and automatically generates output file from the template. This is similar to how Visual Studio generates strongly-typed datasets from .xsd files.

Command Line Utility

T4 also includes a command line utility, TextTransform.exe, which you can use to process templates outside of Visual Studio (similar to xsd.exe for strongly-typed datasets).

Editor

Text editing and debugging support for T4 templates is currently rather limited. I use T4 Editor from Tangible Engineering, which extends Visual Studio to provide IntelliSense and syntax highlighting for .tt files. Another option is the T4 Editor from Clarius Consulting, however functionality of its free edition is more limited.

Debugger

Debugging requires placing calls to Debugger.Break method in code blocks to set breakpoints. Check out this post by Gareth Jones for more details. Hopefully, future versions of Visual Studio will provide a better debugging experience for T4 templates.

Visual Studio Templates

Unfortunately, Visual Studio itself does not provide a specific item for T4 templates in the Add New Project Item dialog. This makes it difficult for developers to discover this code generation tool even exists. You can download T4 Toolbox from CodePlex, which adds several items to the Code Generation folder of the Add New Project Item dialog.

Details

Here are some articles that will help you understand how template transformation works by showing how specific blocks and processing directives are “compiled”. Examples in these articles include the original template text, compiled template code and output file it produces.

The following articles cover advanced topics of code generation with T4.

Videos

Examples

You can find some T4 examples on MSDN. You will notice that it has very limited information about use of T4 outside of DSL and Guidance packages. Here are some examples of standalone templates you can start using without having to build your own Software Factory.

Alternatives

As a code generation tool, T4’s purpose is similar to that of CodeDom (Code Document Object Model). CodeDom provides an API you can use to generate code in any .NET language from the same program. CodeDom API is low-level, complex, and has a steep learning curve. It is typically used for code generation in frameworks that need to to support multiple .NET languages. For example, T4 engine itself uses CodeDom; you have to use CodeDom to extend T4 with custom directives. Compared to CodeDom, T4 is easier to learn and use. However, T4 templates are language-specific. In other words, if you want to generate the same code code in C# and Visual Basic, you will need to create 2 separate T4 templates. Unlike CodeDom, T4 can generate any text files (XML, HTML, etc) and not just .cs or .vb files. This makes T4 a better fit for code generation in application development then CodeDom.

T4 engine is similar to CodeSmith, which has been around a lot longer, provides an excellent set of ready-to-use templates, better template editing and debugging experience for a reasonable price. Unlike CodeSmith, which was was designed to be a template-based code generation tool, T4 engine was designed as a supporting tool for Software Factories. T4 does not offer any reusable templates out of the box and provides rather limited documentation focused on use of T4 templates in DSL and Guidance packages. However, with inclusion in Visual Studio 2008, I think we will see more and more teams adopting T4 engine as a free alternative to CodeSmith.

T4 engine is also similar to NVelocity, an open-source template transformation engine. NVelocity was ported from Java and intends to stay as close to Jakarta Velocity as possible. This makes its template syntax different from ASP.NET and I would think that more people will prefer T4. I don’t know if a significant number of NVelocity templates are available at this time.


Write a Comment

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

Reader Comments

Added a link to new article - <#@ property #> directive.

[…] Sych has a large number of very, very good blog posts about T4, Oleg is THE T4 blogger out […]

[…] An explanatory series […]

[…] them by hand. Furthermore, Ryan Hauert and I were toying around with the idea of using T4 Templates to generate the SQL we needed. In all honesty, we didn’t even consider modifying the […]

Does T4 support runtime invocation? I was thinking of it being ideal for, say, e-mail blasts.

Jon

Jon,

Yes, you can use TransformText.exe to transform templates outside of Visual Studio. However, I don’t think you can redistribute it with an application to users who don’t have Visual Studio installed.

Oleg

DSL and GAT links to Microsoft site are broken.

Hi… the T4 Editor is not free anymore..

Rodrigo, community edition of the T4 editor is still free. It’s a rough equivalent of the beta version Clarius Consulting published previously.

[…] Toolkit (T4) enables you to dynamically build files in Visual Studio projects more at Oleg Sych and Scott Hanselman’s blog - Nikhil Kothari’s Silverlight Fx Library […]

Castle Project has a fork of NVelocity that is actively maintained as opposed to the original project on SourceForge which has not been updated for several years.

Here is the URL of the Castle fork:
http://www.castleproject.org/others/nvelocity/index.html

[…] would also suggest reading Oleg Sych’s posts as an introduction to T4 as they will really help you get started if you have not used T4 before. […]

Excellent article, I just found out how easy the life of the developer has become. Everything can be object oriented right from a basic class to even a database table.
This T4 Template ROCKS!!!

[…] (8) Authoring Blueprints - Using T4 Templates : In this screencast (4:01), Michael Lehman demonstrates how to use T4 templates with Microsoft Blueprints. Only a very basic T4 template is shown which is sufficient for the purposes of the demonstration. For more information on T4, read Oleg Sych’s T4 tutorial series.  […]

[…] Here’s a intro video that’s pretty good (except for the random use of VB and C#).  Also here’s a T4 editor extension for Visual Studio to add syntax highlighting.  Finally, here’s another blog with some good resources and samples. […]

[…] This technology works by using T4 (Text Template Transformation Toolkit) it is a technology that feels a lot like asp.net markup.  So someone who is familiar with MVC […]

[…] also looking at the LINQ-to-SQL T4 templates written by Oleg Sych. T4 was added to Visual Studio as a somewhat unknown feature and you can read […]

I have been doing a lot of research on T4 templates but I can not find an example that shows how to inject a wizard for entering parameters (similar to the MVC controller and view templates) into the process. Has anyone seen a blog/article that can provide an example of this process? Thanks.

[…] if you’ve been reading the Entity Framework Design Blog you will have heard us talk about T4. It is a technology that ships with Visual Studio 2008 (and 2005 as a separate […]

[…] Need on kirjutatud Oleg Sychi poolt, Text Template Transformation Toolkit […]

[…] Entity Framework now leverages T4, Text Template Transformation Toolkit, which makes customizing Code Generation easy, flexible and powerful, and the experience is also […]

I thought CodeDom or xsl based code generation was the only way.
Thanks for pointing out this feature.

Ta,
Rajeesh

[…] To learn more about this, here is the great link - http://www.olegsych.com/2007/12/text-template-transformation-toolkit/ […]

[…] T4: Text Template Transformation Toolkit […]

[…] T4: Text Template Transformation Toolkit […]

Can you write on ‘How to manage spacing while generating code with T4′ and ‘How to effectively write longer templates by splitting into smaller templates’