Wrong indentation with t4 templates
Asked Answered
L

2

19

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;
}
Lippizaner answered 12/12, 2013 at 8:17 Comment(3)
I usually avoided it by making my T4 template more ugly and removing whitespaces in that, so my generated code looked more pretty. :)Blair
Yes but it complicated to understand...Lippizaner
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.Catercorner
A
42

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;
}
Anticoagulant answered 14/12, 2013 at 9:30 Comment(1)
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.Woolsack
A
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.

Ashram answered 14/12, 2013 at 7:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.