在 T4 模板中使用类似 PHP 的函数

Using PHP-like functions in T4 templates

在PHP中可以有一个函数,它的主体从渲染模式切换到代码模式,如下所示:

<?php
 function renderA(a){
   if(a.label){
      ?><label></label><?php
   } else {
      ?><span></span><?php
   }
 }
?>

T4也可以吗? 我的 google 搜索将我带到这里:Is there any way to have functions in basic T4 templates?

但是这个函数定义好像不允许这样。

或者至少,它并不明显...

我知道这段 PHP 代码不是很好的代码,但是当您必须在循环中多次调用 renderA 来呈现某些内容时,它会派上用场。我认为 ASP.MVC-razor 也有类似的东西(),所以我希望 T4 也能以某种方式支持它......

好的。 我在这里找到了答案: How to create a method that encapsulates the T4 template text section?

<# #><#+ #> 的特殊组合似乎可以达到目的。

<#+
public void RenderA(MyClass a){
   if(a.label != null){
      #><label><#= a.text #></label><#+
   } else {
      #><span><#= a.text #></span><#+
   }
}
#>

基本上,您像往常一样使用 <#= #> 进行字符串插值,使用 <#+ #> 继续函数体。

链接问题中还有另一种选择,它使用内联 lambda 声明 ()。