Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an Object to a T4 Text Template

Tags:

c#

.net

t4

I have a T4 Template that I am trying to pass object values to at runtime.

Basically what we're trying to to is:

  1. From a Windows .NET form, read a file as text

  2. Set an external object property to the text value

  3. Access that object property in a T4 text template that has an output extension of .java.

I am starting very simple for now where I just have the template and the form and say an external class object:

Flow

Of course reading the text in the the form part and setting an object property like foo.foocode is fairly straightforward.

I just can't figure out how to access that object variable or property in the template and i've been looking at this for over a day..

Thanks

like image 672
Tikhon Avatar asked Mar 02 '13 23:03

Tikhon


1 Answers

At runtime you can only transform preprocessed templates, because the templating engine is not a redistributable part of Visual Studio. You can pass objects to a preprocessed templates using the parameter directive. The object type you pass to the template must be decorated with the SerializableAttribute. Before calling the TransformText() method put the value of the parameter into the templating session.

The output extension directive is ignored when using a preprocessed template. The TransformText() method returns a string with the generated code. You can save it in whatever file type you want.

<#@ template debug="true" #>
<#@ parameter name="MyObject" type="MyNamespace.MyType" #>

<#
  // now access the passed parameter using
  this.MyObject
#>

Call the preprocessedTemplate:

var templateInstance = new MyTemplate();
templateInstance.Session = new Dictionary<string, object>();
templateInstance.Session.Add("MyObject", new MyType());
templateInstance.Initialize();

var generatedCode = templateInstance.TransformText();

System.IO.File.WriteAllText("outputfile.java", generatedCode);

Hope this helps.

like image 159
Nico Avatar answered Sep 19 '22 02:09

Nico