简体   繁体   English

将对象传递到T4文本模板

[英]Pass an Object to a T4 Text Template

I have a T4 Template that I am trying to pass object values to at runtime. 我有一个T4模板,我试图在运行时将对象值传递给它。

Basically what we're trying to to is: 基本上,我们想要做的是:

  1. From a Windows .NET form, read a file as text 从Windows .NET表单中,以文本形式读取文件

  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. 在输出扩展名为.java的T4文本模板中访问该对象属性。

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. 当然,读取表单部分中的文本并设置诸如foo.foocode之类的对象属性非常简单。

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. 在运行时,您只能变换预处理的模板,因为模板引擎不是Visual Studio的可再发行部分。 You can pass objects to a preprocessed templates using the parameter directive . 您可以使用parameter指令将对象传递给预处理的模板。 The object type you pass to the template must be decorated with the SerializableAttribute . 传递给模板的对象类型必须使用SerializableAttribute装饰。 Before calling the TransformText() method put the value of the parameter into the templating session. 在调用TransformText()方法之前,将参数的值放入模板会话中。

The output extension directive is ignored when using a preprocessed template. 使用预处理模板时,将忽略输出扩展指令。 The TransformText() method returns a string with the generated code. TransformText()方法返回包含生成的代码的字符串。 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: 调用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. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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