For example, you could create a template to define an HTML page:
The date and time now is: <#= DateTime.Now #>
Notice that the template resembles the generated output. The similarity of the template to the resulting output helps you avoid mistakes when you want to change it.
In addition, the template contains fragments of program code. You can use these fragments to repeat sections of text, to make conditional sections, and to show data from your application.
To generate the output, your application calls a function that is generated by the template. For example:
string webResponseText = new MyTemplate().TransformText();
Your application can run on a computer that does not have Visual Studio installed.
To create a run-time template, add a Preprocessed text template file to your project. Alternatively, you can add a plain text file and set its Custom Tool property to TextTemplatingFilePreprocessor.
For more information, see Run-Time Text Generation with T4 Text Templates. For more information about the syntax of templates, see Writing a T4 Text Template.
Typically you would use several templates that read the data in a single input file or database, and generate some of your .cs, .vb, or other source files. Each template generates one file. They are executed within Visual Studio or MSBuild.
For example, your input data could be an XML file of configuration data. Whenever you edit the XML file during development, the text templates would regenerate part of the application code. One of the templates could resemble the following example:
<#@ output extension=".txt" #>
<#@ assembly name="System.Xml" #>
System.Xml.XmlDocument configurationData = ...; // Read a data file here.
namespace Fabrikam.<#= configurationData.SelectSingleNode("jobName").Value #>
... // More code here.
Dependent on the values in the XML file, the generated .cs file would resemble the following:
... // More code here.
As another example, the input could be a diagram of workflow in a business activity. When the users change their business workflow, or when you start work with new users who have a different workflow, it is easy to regenerate the code to fit the new model.
Design-time templates make it quicker and more reliable to change the configuration when the requirements change. Typically the input is defined in terms of business requirements, as in the workflow example. This makes it easier to discuss the changes with your users. Design-time templates are therefore a useful tool in an agile development process.
To create a design-time template, add a Text Template file to your project. Alternatively, you can add a plain text file and set its Custom Tool property to TextTemplatingFileGenerator.
For more information, see Design-Time Code Generation by using T4 Text Templates. For more information about the syntax of templates, see Writing a T4 Text Template.