18

I'm currently working with T4 templates and I have noticed that sometimes the code is not indented properly, how can I avoid that?

For instance I have this code in the template

}
    <# } #>
    this.cmbDecisionList.Dat = dataSource;
    this.btnDec.Enabled = dataSource.Count > 0;
}

and in the generated class it's like

}
                 this.cmbDecisionList.Dat = dataSource;
      this.btnDec.Enabled = dataSource.Count > 0;
}
Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
John Jerrby
  • 1,683
  • 7
  • 31
  • 68
  • I usually avoided it by making my T4 template more ugly and removing whitespaces in that, so my generated code looked more pretty. :) – Allan S. Hansen Dec 12 '13 at 09:48
  • Yes but it complicated to understand... – John Jerrby Dec 12 '13 at 09:53
  • 1
    Usually generated code is not intended to be read, but i know your desire to have nice looking code, even if it's generated automatically. Besides changing your T4 template you can also use the "Format Document" option in the "Edit" > "Advanced" Menu on your output file. And as far as I know tangible's T4 Editor has a "Format output" option when generating code. – Nico Dec 12 '13 at 16:14

2 Answers2

41

Allow me to illustrate your problem by replacing spaces with dots.

}
....<# } #>
....this.cmbDecisionList.Dat = dataSource;
    this.btnDec.Enabled = dataSource.Count > 0;
}

and in the generated class it's like

}
........this.cmbDecisionList.Dat = dataSource;
    this.btnDec.Enabled = dataSource.Count > 0;
}

Now, let us remove the preceding dots.

}
<# } #>
....this.cmbDecisionList.Dat = dataSource;
    this.btnDec.Enabled = dataSource.Count > 0;
}

and in the generated class it's like

}
....this.cmbDecisionList.Dat = dataSource;
    this.btnDec.Enabled = dataSource.Count > 0;
}
Phillip Scott Givens
  • 5,256
  • 4
  • 32
  • 54
  • 6
    I could almost cry at the sight of such a simple but accurate description of the solution to this problem which has been bothering me for quite some time now. Thank you. – stvn Jul 17 '15 at 08:05
12

I think it's good that you strive for readable generated code. We will sit and try to debug the generated code occassionally so it's good if it's easy on the eyes (ofc we never edit the generated code).

I have adopted a pattern where I might sacrifice some readability of the template to gain generated code readability.

Generated code
<#
    T4 statements
#>
Generated code

IE #> always appear after a newline and a newline is added immedietly after.

Your code then would be changed into:

}
<# 
    } 
#>
    this.cmbDecisionList.Dat = dataSource;
    this.btnDec.Enabled = dataSource.Count > 0;
}

That way the generated code tends to be formatted as intended.

It's probably not the only way to retain the formatting as intended but it's the one I use.

Hope this helps.