How to create a method that encapsulates the text section of a T4 template?

Instead, .tt:

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ import namespace="System.IO" #>
<#@ output extension=".txt" #>
<#@ assembly name="System"#>

<# message = "hello world" ; #>

blah blah blah etc. very complex example with embedded expression like
<#=message#>

I would like to have an output function that will return the output of blah blah, etc .:

    <#@ template debug="false" hostspecific="true" language="C#" #>
    <#@ import namespace="System.IO" #>
    <#@ output extension=".txt" #>
    <#@ assembly name="System"#>

    <#output();#>

   <#+ output() { #>
   blah blah blah etc. very complex example with embedded expression like
    <#=message#>

   <#}
   #>

Of course, the syntax above is incorrect. How to do it?

+5
source share
2 answers

In fact, you are very close to what you have. I find this helps remember that the template is essentially a C # / VB class under the hood, so when you use the <# + #> block, you really just add a member to the class.

, < # + # > , , , TransformText(), < # # > .

<#+ public void output() { #>
blah blah blah etc. very complex example with embedded expression like     <#=message#>

<#+ }
#>
+6

<#+ ... #>. lambda <# ... #> :

<#@ template language="C#" #>
<#@ output extension=".txt" #>

<# Action output = () => { #>
loooooooong text <#= "message" #>
<# }; #>

<# output(); #>

:

loooooooong text message
+6

All Articles