在 T4 预处理模板中调用 Transformtext() 方法中的方法 [英] Call Methods in Transformtext() Method at T4 Preprocessed Template
问题描述
我使用 T4 和预处理模板来生成一些代码.因此,当我直接在 .tt 文件中添加所有模板时,一切正常,如下所示:
I use T4 and Preprocessed Template to generate some codes. So When I add all of the templates directly in .tt file every things is OK like the following:
<#@ template language="C#" #>
<html><body>
<h1>Sales for Previous Month</h2>
<table>
<# for (int i = 1; i <= 10; i++)
{ #>
<tr><td>Test name <#= i #> </td>
<td>Test value <#= i * i #> </td> </tr>
<# } #>
</table>
This report is Company Confidential.
</body></html>
但是我需要在一些方法中对代码进行分组并在transformText()
方法中调用方法:
But I need to grouped codes in some methods and call methods in transformText()
Method:
MyTemplate.tt 文件如下:
MyTemplate.tt file is like the following:
<#@ template language="C#" #>
<#+
private string header(){
#>
<html><body>
<h1>Sales for Previous Month</h2>
<#+
return this.GenerationEnvironment.ToString();
}
private string body() {
#>
<table>
<#+ for (int i = 1; i <= 10; i++) { #>
<tr><td>Test name <#= i #> </td>
<td>Test value <#= i * i #> </td> </tr>
<#+ } #>
</table>
<#+
return this.GenerationEnvironment.ToString();
}
private string footer(){
#>
This report is Company Confidential ..
</body></html>
<#+
return this.GenerationEnvironment.ToString();
}
#>
和相关的MyTemplate.cs文件如下:
And related MyTemplate.cs file is like the following:
// ....
public virtual string TransformText()
{
return this.GenerationEnvironment.ToString();
}
// ....
所以我像这样调用 TransformText()
方法中的方法:
So I call the methods in TransformText()
method like this:
// ....
public virtual string TransformText()
{
header();
body();
footer();
return this.GenerationEnvironment.ToString();
}
// ....
所以一切都还好,但是如果我更改 .tt 文件中的任何内容并保存它,.cs 文件将再次重新生成并且 TransformText()
方法返回到第一个实现(没有任何调用)?
So every thing is OK yet, but if I change any thing in .tt file and Save it, the .cs file regenerated again and TransformText()
Method return to first implementation (without any calling)?
那么如何在预处理模板中使用一些方法并生成代码?你的建议是什么?
So how can I use some methods and generate codes in Preprocessed Template? What is your suggestion?
推荐答案
这行得通吗?
<#@ template language="C#" #>
<#
header ();
body ();
foooter ();
#>
<#+ ... the rest ... #>
附注.不知道为什么要在页眉、正文和页脚内部调用
PS. Not sure why you call inside header, body and footer
return this.GenerationEnvironment.ToString();
这篇关于在 T4 预处理模板中调用 Transformtext() 方法中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!