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

后端 未结 2 1649
悲哀的现实
悲哀的现实 2021-02-10 00:26

Instead of this .tt:

<#@ template debug=\"false\" hostspecific=\"true\" language=\"C#\" #>
<#@ import namespace=\"System.IO\" #>
<#@ output extens         


        
相关标签:
2条回答
  • 2021-02-10 00:40

    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
    
    0 讨论(0)
  • 2021-02-10 00:46

    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#>
    
    <#+ }
    #>
    
    0 讨论(0)
提交回复
热议问题