Indent T4 in generated C # code

When using T4 to generate C # code, I cannot get the correct identification with the TABS scattered around:

public partial class Foo : Base
{
        public int C { get; set; }
        [MappedProperty("A.B[{C}].Foo")]
    public int Foo { get; set; }
}

I am using a seemingly correctly typed .TT code similar to the following:

public partial class <#= ViewModelName #>
{
    <#  foreach(var property in ViewModelProperties) { #> 
        <# if(property.Mapping != null) { #>
        [MappedProperty("<#= property.Mapping #>")]
        <# } #>
        public <#= property.TypeDeclaration #> <#= property.MemberName #> { get; set; }
    <# } #>
}

This piece of code reflects what I have already tried to do: simplify control statements and blocks in one line as much as possible.

+4
source share
3 answers

I like to do it like this and there have never been any problems.

public partial class <#= ViewModelName #>
{
<#
    foreach(var property in ViewModelProperties) { 
        if(property.Mapping != null) { 
#>
    [MappedProperty("<#= property.Mapping #>")]
<#
        }
#>
    public <#= property.TypeDeclaration #> <#= property.MemberName #> { get; set; }
<#
    }
#>
}
+6
source

Use PushIndent(), PopIndent()and ClearIndent():

public partial class <#= ViewModelName #>
{
<# PushIndent("   "); #>
<#  foreach(var property in ViewModelProperties) { #> 
<# if(property.Mapping != null) { #>
[MappedProperty("<#= property.Mapping #>")]
<# } #>
public <#= property.TypeDeclaration #> <#= property.MemberName #> { get; set; }
<# } #>
<# PopIndent(); #>
}

or alternatively ...

public partial class <#= ViewModelName #>
{
<# 
   PushIndent("   "); 
   foreach(var property in ViewModelProperties) {
      if(property.Mapping != null) { 
         WriteLine("[MappedProperty({0})]", property.Mapping);
      }
      WriteLine("public {0} {1} {{ get; set; }}", property.TypeDeclaration, property.MemberName);
   }
   PopIndent(); 
#>
}
+2
source

'< #', :

  • '< #' , foreach if . , .

  • Your line publicstarts with a double tab, so it generates an indented property with a double tab instead of one. Remove it.

  • all spaces outside the tags '<#' will be printed, delete them, leave only what is needed outside the tags (before and after them). Otherwise, they accumulate and violate your formatting.

+1
source

Source: https://habr.com/ru/post/1614280/


All Articles