T 4 beginners – part 1
this is the first post of a series that will focus on T4 template.
this post discuss the T4 in general while the following pose will focus on the T4 practice.
the code for this post can be found here.
What is T4 template?
T4 is sanding for Text Template Transformation Toolkit.
T4 is all about automating code or content generation.
the usual extension for T4 files is the *.tt
When to use T4?
whenever you identify repeatable pattern of code or content, that can be
infer from other item within the project (like the case of code that is
generate from a designer, or entity framework self tracking entities),
you should consider to automate it by using T4,
instead of writing it over and over again.
What are the benefits?
T4 can bring the following benefits:
- speed-up the development process.
- increase the code consistency.
- make is easier to apply best practice.
- it is easy to start with prototype then modify it’s dynamic sections.
- T4 is very powerful concept because it is using C# or VB.net as it script language,
therefore it is lower the learning curve.
The T4 structure
T4 are composed of the following parts:
Directives – elements that control how the template is processed.
<#@ output extension=".txt" #>
Text blocks – content that is copied directly to the output.
Control blocks – program code that inserts variable values into the text,
and controls conditional or repeated parts of the text.
<#= System.DateTime.Now.ToString() #>
T4 syntax resemble old ASP 3 syntax, it is an hybrid of text and <# control blocks #>
we will discuss each T4 command in the following part of the series, but in general:
lines 1-6: are directives.
Line 12 and lines 17,18: has control blocks.
any thing else is just text blocks.
the project will look as follow:
the generated HelloWorld.cs will look as follow:
notice that the date at line 5 and part of the text at lines 10, 11 was generate by the T4.
What do you need to get it operating?
T4 is part of Visual Studio 2010, which mean that you can add T4 template to any of
your project (just by adding item and selecting one of the T4 item template).
what’s missing is the IntelliSense and syntax coloring capability.
you can add the syntax coloring and IntelliSense by installing the following VS extension gallery:
T4 can boost your coding productivity by automating repeatable patterns.