In this article, we will look into T4 templates and how they are helpful in code/documents generation. We can create templates and generate code/text based on it without need of searching and replacing text in it. T4 templates are used to generate boiler-plate code by MVC, Entity framework. We can create two types of templates:
Text template [Design time]: used to generate code to be used at design time by other classes and can interact with model designers.
Runtime Text Template [preprocessed]: used to generate and execute it via code, support passing parameters and can execute outside of Visual Studio.
Let’s create a sample console application in Visual Studio 2015 and understand it:
Click on Add new item in Solution Explorer and select Text template as shown below, which will add .tt file to our project:
Let’s add below code and run it:
Here, I used T4 output directive (<#@ directivename attribute=”value” #>) that will give instructions to template engine to generate output file with .txt extension and should be first elements in the template.
We can use import directive to use a specific assembly in the template without fully qualified name, assembly directive for using it in the template and template directive to set attributes like debug flag to enable/disable template debugging, language flag [C# or VB] and inherits attribute to set base class for generated class.
We can add an expression block (<#= Expression #>) to compute an expression and return result within a text block (here, output is current Datetime).
We can save template or click on Run Custom Tool to execute the it and generate .txt file with current date time:
Output:
Let’s extend our template by adding statement blocks (<# statements #>), which can have multiple statements with variables, loops and other control statements in it:
Output:
Here, we used utility method WriteLine (or) Write to show text in text file.
I am ending things here, inthe next article I will drill down more on T4 Templates and look into class feature blocks and template parameters etc. I hope this article will be helpful for all.
Read more articles on Visual Studio 2015: