Blank lines in files generated by T4 templates
Why does my T4 text template (.tt) generate a code file full of empty lines?
After checking out an old solution and running a T4 template (.tt file) that used to work perfectly, I found that the output included a whole heap of additional line breaks.
// The template looks like this:
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#
// Code to do things
#>
public class Foo() {
....
}
The output looked like this:
// The output looks like this:
public class Foo() {
....
}
There were also additional blank lines within the body of the generated class - with a blank line being present wherever a T4 tag was closed and a new line started (i.e. #>
). After a bit of digging and experimentation I found that the file was checked out with LF
line endings instead of CRLF
line endings.
It seems that a line ending of \r\n
after a closing tag is completely omitted, but if the line ending is just \n
it won't be omitted and will actually be rendered out to the generated document.
The fix?
A find/replace to change changing each \n
to a \r\n
and then re-running the T4 template generated the correct output:
// The fixed output without any extra empty lines:
public class Foo() {
....
}