Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a t4 file with user input?

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.

like image 309
Taylor Mitchell Avatar asked Oct 28 '25 14:10

Taylor Mitchell


1 Answers

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

like image 104
crthompson Avatar answered Oct 31 '25 05:10

crthompson