T4 stands for Text Template Transformation Toolkit and is Microsoft's free and open-source template-based text generation framework included with Visual Studio.
T4 is used by developers to automate repetitive text file creation processes. Text files can be anything from HTML code, XML, XAML and most often compilable code files (Visual Basic, C# or other languages).
T4 uses a custom template format which can contain C# or Visual Basic executable code along with string literals that become part of the generated file.
Advantages
Visual Studio integration
Whenever a developer creates and saves a file with extension *.tt, Visual studio automatically runs the T4 templating engine and processes the saved template. There's no need to run any external tool which makes it transparent for developers to use.
.NET language support
It's easier for developers to use something that they know rather than reinventing the wheel. Developing T4 templates is very similar to writing ASPX files where executable code sits along string literals (HTML code interpreted by the client browser) and manipulates it as required.
Disadvantages
Lack of Visual Studio tooling support
It's possible to write and save T4 templates inside Visual Studio but developers won't have any other advantages of a modern development environment like code formatting/colouring or code IntelliSense. Third-party tools are required to provide this functionality. Available extensions include Tangible T4 Editor and Devart T4 Editor among others.
One template, one output file
It's sometimes desired for a template to process several resources (either files, database tables, etc.) at once and output just as many text files. By default, T4 doesn't support multiple file output. But there are solutions to overcome this limitation as well.
Usage
There are lots of different usage scenarios for T4 templates that can greatly benefit developers to shorten their development time. There are templates on the internet for:
- LINQ to SQL/EF code generation
- T4MVC template to generate strongly typed ASP.NET MVC helpers
- T4CSS template to automatically generate CSS files from less verbose LESS format
enum
generation from a database lookup table generic template- etc.
Microsoft also uses T4 templates for ASP.NET MVC controller and view generation when developers add a new Controller or View from within Visual Studio.