T4 Lessons Learned

Working with T4 recently I learned a couple of valuable lessons I’d like to share.

Lesson 1: Template Language
One of the parameters of the language directive is the language, which specifies the language used in the code blocks of the template. Two languages are specified, C# and VB.

However, any attempts to use var, lambdas, initialization lists or even inheritance failed. And then I found the answer to the problem on Oleg Sych’s great blog. In VS2008 you can specify which version of the language you want to use. For instance v3.5 for using C#/VB.NET 3.5

Then, suddenly, all of these missing features worked!

Lesson 2: Generate Multiple Output Files

There are cases when you want a T4 template to generate, not one, but several output files. And of course, you want the automatically added to the project, source control, all menu. For instance, maybe you want to generate files for a database object model. You have a single template that parses the description of the model and generates code, but the code should be put in different files.

Here is a dummy example, that produces five EntityX classes, all on the same file.

However, with the help of this script by Damien Guard you can define blocks that get generated in different files. You can also define common blocks, such as header and footer for all output files. What you have to do is:

  • include the script into your template
  • create an instance of the blocks manager
  • define file blocks
  • optionally define header and footer blocks
  • process the blocks at the end of the template

Here is a concrete example for the above example:

The result is five EntityX classes are generated, each in a separate file called EntityX.cs, and all these files are automatically added to the project.

, , , Hits for this post: 10897 .
Trackback

2 comments untill now

  1. Gravatar

    Dear Marius,
    in your example, don’t you also get a .cs file with the template base name generated ? (in addition to the EntityX.cs files) …that ‘s what I am getting when I tried out your example .
    Regards,
    Jean

  2. Gravatar

    I do get an additional .cs file, with the same name as the TT file, except the extension is .cs, but that file is empty, so I don’t have any problems compiling the project, even though it’s added to the project.

Add your comment now