I have a T4 Template that I am trying to pass object values to at runtime.
Basically what we're trying to to is:
From a Windows .NET form, read a file as text
Set an external object property to the text value
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:
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
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.
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