0

In PHP it is possible to have a function that its body switches from rendering-mode to code-mode like so:

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

Is this possible in T4 too? My google search led me here: Is there any way to have functions in basic T4 templates?

But this function definition does not seem to allow this.

Or at least, it is not obvious that it does...

I know this PHP code is not pretty code, but it comes handy when you have to call renderA many times in a loop to render something. I think ASP.MVC-razor has something similar as well (https://stackoverflow.com/a/6532107/2173353), so I would expect T4 to support this too somehow...

user2173353
  • 4,316
  • 4
  • 47
  • 79
  • Yes, it's possible to scoping code by marking with `<# ... #>` block (see Entity Framework generated T4 template from EDMX as example). What exactly you want to try with T4 template? – Tetsuya Yamamoto Oct 16 '17 at 08:54
  • @TetsuyaYamamoto I just want to create a function that has C# code and HTML rendering inside it, as in the PHP example above. So far, I have only seen functions with pure C# code (no html rendering done inside them). Do you have a link for this E.F. example that you mention? – user2173353 Oct 16 '17 at 08:58
  • @user2173353 The rendered code is still C# code, you can't magically make PHP-style functions. – DavidG Oct 16 '17 at 08:59
  • @DavidG I don't know if I understood your comment right, but I know I should write the code in C# inside the function and not in PHP code, just I want the code/html switching ability that PHP has. Something similar to the ASP.MVC razor syntax presented here: https://stackoverflow.com/a/6532107/2173353. Razor **does** support this and it is C# code. – user2173353 Oct 16 '17 at 09:04

1 Answers1

0

OK. I have found an answer here: How to create a method that encapsulates the T4 template text section?

It seems that a special mix of <# #> and <#+ #> can do the trick.

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

Essentially, you use <#= #>, as usual, for string interpolation and <#+ #> for continuing with the function body.

There is also another alternative in the linked question that uses an in-line lambda declaration (https://stackoverflow.com/a/23840134/2173353).

user2173353
  • 4,316
  • 4
  • 47
  • 79