I am trying to make a generator for cs files through commandline. I want to use T4 because I'm not really aware of another way to generate files and move them easily. The problem I'm having is trying to pass user input data to the T4 Files.
For Example the user in my program would input their name
Bob
My T4 template I want the output to be
Hello Bob
I can't seem to pass data to it unless I wrote it to a text file and read it from it. Is there another way that I could do this? At some point I need it to handle collections of attributes which could be a pain to read properly in a text file.
Using a T4 parameter directive you can pass values from the app domain into your T4 template.
Create a parameter:
<#@ parameter type="Full.TypeName" name="ParameterName" #>
Put it in your template:
<#@ template language="C#" #>
<#@ parameter type="System.String" name="MyUserName" #>
<# Console.Write(MyUserName) #>
Populate it from code:
// Get a service provider – how you do this depends on the context:
IServiceProvider serviceProvider = dte; // or dslDiagram.Store, for example
// Get the text template service:
ITextTemplating t4 = serviceProvider.GetService(typeof(STextTemplating))
as ITextTemplating;
ITextTemplatingSessionHost host = t4 as ITextTemplatingSessionHost;
// Create a Session in which to pass parameters:
host.Session = host.CreateSession();
// Add parameter values to the Session:
session["MyUserName"] = "Bob";
// Process a text template:
string result = t4.ProcessTemplate("MyTemplateFile.t4",
System.IO.File.ReadAllText("MyTemplateFile.t4"));
Another helpful link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With