6

Instead of this .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'd like to have an output function that would return the output 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 not correct. How to do this ?

user310291
  • 36,946
  • 82
  • 271
  • 487

2 Answers2

9

This is an alternative solution not using class feature blocks <#+ ... #>. Using a lambda expression inside usual statement blocks <# ... #> allows defining a local function as follows:

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

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

<# output(); #>

This template produces the output below:

loooooooong text message
isaias-b
  • 2,255
  • 2
  • 25
  • 38
6

Actually you're very close with what you've got there. I find it helps to remember that the template is essentially a C#/VB class under the hood, so when you use a <#+ #> block, you're really just adding a member to the class.

Once you've started using the <#+ #> notation, you have to keep using it, as you're still adding stuff to the class at the member level, not adding the the TransformText() method which regular <# #> tags do.

The correct syntax would be

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

<#+ }
#>
GarethJ
  • 6,496
  • 32
  • 42