T4: Text Template Transformation Toolkit


Watch Overview on Channel 9

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 […]

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’

[…] Sych has a lot of good info on T4 […]

[…] Templating Explained (http://www.olegsych.com/2007/12/text-template-transformation-toolkit/, […]

[…] is the basic syntax of T4 templates. Oleg Sych did a great job of explaining the T4 engine from the very basic topics to some more advanced scenarios of how to reuse the templates across different projects and […]

[…] ignorant of the fact they even exist until I see them used or read about them somewhere else. T4 text generation is no exception.  This is a very useful tool that’s built right into Visual Studio 2008 […]

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

[…] Oleg Sych’s Resources on T4 […]

I’m looking to get at the CompiledTemplate and I recall seeing somewhere that here was a custom tool option that would do this.
So this would reduce t4 to syntactic sugar for writing code-generation code that is utilized at runtime.

Let me know if you have any suggested reading or links for this.

Thanks, I appreciate the series of posts it has been a great help.

Bas

[…] it is, fix it you should (Tess Ferrandez blog) INETA North America CTDOTNET Community Credit T4 Oleg Sych - » T4: Text Template Transformation Toolkit T4 (Text Template Transformation Toolkit) Code Generation - Best Kept Visual Studio Secret T4 […]

[…] This is going to Generate a 4T File. 4T Stands for Text Template Transformation Toolkit […]

[…] for Entity Framework. Downloading this and installing into Visual Studio allows the creation of T4 templates according to the schema already defined in the Entity Model we created earlier, and […]

[…] stands for Text Template Transformation Toolkit, and is a template engine that ships with Visual Studio. The Entity Framework POCO Template […]

[…] definitive online guide for T4 information is at http://www.olegsych.com/2007/12/text-template-transformation-toolkit/ Share Uncategorized, Visual Studio Articles Customize the Start Page in Visual […]

[…] de "Blogging.Context.tt" e o outro é chamado de "Blogging.tt". T4 representa Text Template Transformation Toolkit, e é um modelo de motor que vem com o Visual Studio. O Entity Framework POCO Template aproveita o […]

First of all I want to thank you for T4 toolbox - it’s a great addin for VS.
I am writing here about adding new templates to toolbox. Recently I started to use dbml files as a data access layer for stored procedures and several database tables but found that for more complicated things it is not enough and need to write POCO classes as models and then map them to L2S. Yes, I know about EF4 but currently have no possibility to use it.
So I started to look for T4 template which can generate POCO classes from .dbml files. After googling I’ve found such template which can generate POCO classes from .dbml and .edmx. I found it as a very useful thing.
It contains one file which parses dbml xml and provide you information wrote there in own properties.
Second file uses first and actually generates POCO classes. It looks very easy to use it for own needs.
I thought that somebody may have the same problem so want to give a link to the resource where I found those templates (link for downloading is in the bottom of the article).
http://blog.tonysneed.com/2009/01/16/t4-poco-templates-for-l2s-and-ef/

[…] z pliku Labels.resx (w którym umieszczane są wielojęzykowe wersje nagłówków), oraz Text Template Transformation Toolkit (T4). Zacznijmy od napisania pliku generującego nam klasę stałych tekstowych pobranych z pliku […]

[…] “Blogging.Context.tt” e o outro é chamado de “Blogging.tt”. T4 representa Text Template Transformation Toolkit, e é um modelo de motor que vem com o Visual Studio. O Entity Framework POCO Template aproveita o […]

[…] Transformation Toolkit By yjhwang Closed Categories: Shortcuts (dev) Tags: T4 URL : http://www.olegsych.com/2007/12/text-template-transformation-toolkit/ Tags .Net Automation C++/CLI CodeDOM Interop MEF MVVM Pattern T4 WPF […]

[…] describing it in detail in this post as Scott Hanselman has a good introduction on his blog, and Oleg Synch has a great set of tutorial articles on it. Put simply, T4 lets me write some code that will […]

[…] Sych http://www.olegsych.com/2007/12/text-template-transformation-toolkit/ .Net, Development, Link List, T4, VB.net Code Gen, T4, Text Template, […]

[…] also: T4: Text Template Transformation Toolkit (Oleg Sych blog) Understanding T4-MSBuild integration Posted by Ivan @ 15:22 :: Tools Comment […]

Text Transformation is what this technique (technology) does. Why is doesn’t the basic example involve transformation. This introduction, as pretty as it may be, is not as useful as I would have liked. When I read “transformation,” I generally expect:

[input] -> {map} -> [output]

Then the issues are what does the input look like, how to specify the map, and what does the output look like. And, last but not least, how are these seated within Visual Studio and its automated processes, typically (including assembly references).

That’s it.

George,

I think the name says Text Template Transformation Toolkit.

Oleg

[…] is a very simple example. Created just for fun and to demonstrate basics of T4, Check the Oleg Sych site for more info and tutorials. He has created a bunch of great materials about […]

[…] Comments 0 A complete series of T4 tutorials written by Oleg Sych […]

[…] Intro to T4 […]

[…] Intro to T4 […]

[…] “Blogging.Context.tt” and the other is called “Blogging.tt”. T4 stands for Text Template Transformation Toolkit, and is a template engine that ships with Visual Studio. The Entity Framework POCO Template […]

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

Excellent blog!!! How can I generate .net projects through T4? I have a .edmx with my model and a T4 template. I need to generate different projects architect ($name_solution.models, $name_solution.data.EF, $name_solution.interface, etc.)

[…] on a schema. I’m not an expert, but if you would like to be one, Oleg Sych’s tutorials here would probably be a good place to start. Scott Hanselman has also blogged about them here and […]

[…] This is a very simple example. Created just for fun and to demonstrate basics of T4, Check the Oleg Sych site for more info and tutorials. He has created a bunch of great materials about […]

Any T4 example using log4net?
I can’t make it work.
Thanks!

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

[…] you want to go in deep, Oleg Sych wrote excellent series of post on […]

[…] scaffolding project on which I’m working, I’m trying to decide whether to use Oslo, T4 or CodeDom for generating code. Our goals are to keep dependencies to a minimum and drive code […]