Coding blog

Introduction to Text templates (T4)

In the following (and first) serie of posts, I will try to introduce one nifty feature that deserves more recognition than it currently has: text generation using T4 templates. If you are an avid Microsoft developer, you probably have used T4 when manipulating the Entity Framework. But before talking about examples of this feature (which will be described in further articles), let’s start with the basics.

Visual Studio comes with an executable called “TextTemplateGenerator” that can interpret a script, and produce a text file from it. This tool is integrated in Visual Studio. In VS2008, you had to create a text file, and change his extension to “.tt” (Text template, once more…). In Visual studio 2010 or 2011, you can directly add a “Text template” item to your projects.

Visual Studio Solution

As soon as you add a tt file to your project, VS configures it to be processed by the TextTemplateGenerator apps as soon as:

  • You save the .tt file
  • You press the “Generate all templates” button in the solution explorer.

Generate All Button

The generated content is added as a child file of the script file. The generated file is by design always named like the script file, but with another extension. The extension is .txt by default, but you can change it to whatever you want (.cs, .vb, .html, and even .java …) by tweaking some parameters in the script file.

Expanded TT

As in PHP, what you write in this text template file is outputted directly by default. You can write code enclosed in scripts tags (<#, <#@, <#+, <#= and so on) that will be executed at parsing time.

The text template <# for (int i=0; i<10; i++) { #> Hello World! <# } #> will output “Hello World!” ten times, as you would have imagined.

Scripts are written in C# by default, but you can change it to VB as you wish. The script has a full access on all .NET features, including all the object-oriented features, files I/O, XML parsing and outputting, web services access, introspection, CLR assembly loading, interop and so on. There are also easy ways to interact with Visual studio (using EnvDTE), in order to append files to the current project, remove them, checkout them, etc.

T4 can be used for many purposes, including generating code, making reports on the code, modeling a customer field of operations etc. In the next posts, I will focus on some practical examples of T4. The first one will be about Web services.

Tags: T4, Code Generation

No Comments

Add a Comment