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

狂风中的少年 提交于 2019-12-21 02:19:07

问题


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 ?


回答1:


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



回答2:


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#>

<#+ }
#>


来源:https://stackoverflow.com/questions/4640623/how-to-create-a-method-that-encapsulates-the-t4-template-text-section

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