2011-12-21 88 views
3

是否有任何命令可以轻松控制T4模板输出空格?我得到了一些过度的tab。。我以为我想起了一个办法来控制模板空白...T4模板空白控件

回答

4

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

不要格式化你的可读性模板。你必须控制块之外的任何空格将在输出

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

最终将结束作为

Hello 
     Hello 
     Hello 
     Hello 
     Hello 
     Hello 
+1

“不要格式化您的模板以提高可读性”让我非常难过。 :( – 2015-11-04 19:25:19

+0

请参阅下面的Josh.M的回答,你放置指令的地方决定了代的起点,将它们保留在位置0以获得更多的控制,并且如果在指令后没有文本,它会影响你的换行符格式化模板输出是非常有可能的,但需要花费很大的努力,但我更喜欢这样做,因为它在调试时节省了时间,当我创建一个新模板时。 – Volkirith 2017-08-29 10:19:52

2

有可能没有很大的修复到这一点,这是与T4发动机本身的问题, IMO。但是,如果您要在保留指令嵌套的同时减少输出中的前导制表符/空格,则可以执行以下操作。

以前

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

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

例如在第0列开始指令,在指令本身内缩进!除此之外,你可能要修剪多余的线条:

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(); 
} 

因人而异

2

只是柜面有人正在使用WriteLine方法添加标签。转义字符起作用。

<# 
for(int i=0; i < 10; i++) 
{ 
    this.WriteLine("\tHello"); 
} 
#>