Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T4 template whitespace control

Tags:

t4

Are there any commands to easily control T4 template output whitespace? I'm getting some excessive tabbing. I thought I remembered a way to control template whitespace...

like image 363
Shlomo Avatar asked Dec 28 '22 08:12

Shlomo


2 Answers

PushIndent, PopIndent, ClearIndent http://msdn.microsoft.com/en-us/library/bb126474.aspx

Do not format your template for readability. Any white space you have outside of control block will end up in the output

for(int i=0; i < 10; i++) 
{
   #>
     Hello
    <#
}

will end up as

   Hello
      Hello
      Hello
      Hello
      Hello
      Hello
like image 121
ILovePaperTowels Avatar answered Jan 15 '23 01:01

ILovePaperTowels


There's probably no great fix to this, it's a problem with the T4 engine itself, IMO. But if you're trying to reduce leading tabs/spaces in your output while preserving directive nesting you can do the following.

Before

<# for (...) { #>
    <# if (...) { #>
        SomeText
    <# } #>
<# } #> 

After

<# for (...) { #>
<#     if (...) { #>
        SomeText
<#     } #>
<# } #>

E.g. start your directives at column 0, indent within the directive itself! In addition to this, you may want to trim extra lines:

private void TrimExtraneousLineBreaksAfterCommentsFromGeneratedFile(ref string fileText)
{
    Regex regex = new Regex(@"(//.+?)(?:\r?\n){2,}");

    // Replace multiple coniguous line breaks, after a comment, with a single line break.
    fileText = regex.Replace(fileText, "\r\n");
}

private void TrimExtraneousLineBreaksFromGeneratedFile(ref string fileText)
{
    Regex regex = new Regex(@"\r?\n(?:\s*?\r?\n)+");

    // Replace multiple coniguous line breaks with 2 line breaks.
    fileText = regex.Replace(fileText, "\r\n\r\n");

    // Remove spaces/line breaks from the file.
    fileText = fileText.Trim();
}

YMMV

like image 21
Josh M. Avatar answered Jan 15 '23 01:01

Josh M.