Call Methods in Transformtext() Method at T4 Preprocessed Template

蹲街弑〆低调 提交于 2019-12-12 03:58:07

问题


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>

But I need to grouped codes in some methods and call methods in transformText() Method:

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();
}
#>

And related MyTemplate.cs file is like the following:

// .... 

public virtual string TransformText()
    {
        return this.GenerationEnvironment.ToString();
    }
// .... 

So I call the methods in TransformText() method like this:

// .... 

 public virtual string TransformText()
    {
        header();
        body();
        footer();
        return this.GenerationEnvironment.ToString();
    }
// .... 

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?


回答1:


Would this work?

<#@ template language="C#" #>
<#
    header ();
    body ();
    foooter ();
#>
<#+ ... the rest ... #>

PS. Not sure why you call inside header, body and footer

return this.GenerationEnvironment.ToString();


来源:https://stackoverflow.com/questions/12988124/call-methods-in-transformtext-method-at-t4-preprocessed-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!