A T4 ("Text Template Transformation Toolkit") template is a text generation tool that mixes raw text and code to generate text as output.
In my last article, I showed how to create a Runtime Text Template and generate output from it via the following lines of C# code:
But sometimes, it is helpful to pass parameters from your C# code and use them in your template.
The steps to do this are:
Add a T4 Runtime Text Template to your Visual Studio project In the T4 template:
- Add one or more parameter directives
- Use the parameters in your template
In your C# code
- Instantiate your T4 template object
- Set the Session property to a new Dictionary
- Pass the parameters in the Session object
- Initialize the T4 template object
- Generate the output text with the T4 template object's TransformText() method.
An example will help illustrate this.
I have a T4 Runtime Text Template named "ParamTemplate1.tt" and I want to add 2 parameters: firstName and lastName (both strings) and use them in my template.
At the top of the template file, add the following directive:
Notice that we included the Namespace in the parameters' data types.
Now, use the parameters in your template, as in the following code:
In your C# program, add the following code
This passes the values "David" and "Giard" to the firstName and lastName parameters, respectively.
We can even pass in a custom data type, based on a type we create.
Imagine I have created a Person class with a FirstName and a LastName properties (both strings) and I want to pass a parameter of this type into my T4 template named "ParamTemplate2.tt" and use that parameter inside the template.
Here is an example of my custom Person class:
In my T4 template, I again add a parameter directive, as shown below:
Notice the custom namespace in the Type.
Now, I can use the parameter and its properties in my template, as shown below:
My C# code is very similar to the first example.
You can find this code in my GitHub repository at https://github.com/DavidGiard/Demo-T4-Parameters.
In this article, I showed how to pass parameters into a T4 Runtime Text Template.