简体   繁体   中英

Pass an Object to a T4 Text Template

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:

流

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM