2014-09-12 52 views
1

在stringtemplate-4中,如何生成多行註釋?例如,模板是這樣的(註釋的開始和結束都在其他一些模板):如何生成多行註釋

test(DESCRIPTION) ::= << 
* 
* <DESCRIPTION> 
* 
>> 

和說明是一個很長的字符串,也可能包含在其中線的飼料,如:

"This is a small description of the program, with a line-width of 50 chars max, so the line is split.\nFinal line." 

因此,我們要輸出字符串,如:

* 
* This is a small description of the program, 
* with a line-width of 50 chars max, so the 
* line is split. 
* Final line. 
* 

回答

0

它看起來像你想要做一些事情這裏 - 把描述上與阿斯特里斯開始 線k,但如果有換行或長度大於50,則將其單獨放在 上。

首先,我將視圖模型中的描述在傳遞給模板之前,根據換行符和長度將其分解。

然後,我會對模板做一些小改動,以便用 分隔數組中的每個項目換行符和星號。

下面是組文件test.stg:

group test; 

description(lines) ::= << 
* 
* <lines; separator="\n* "> 
* 
>> 

我不知道您使用的視圖模型的語言,但這裏的一些Java:

public static void main(String[] args) { 
    STGroup templates = new STGroupFile("test.stg"); 
    String description = "This is a small description of the program, with a line-width of 50 chars max, so the line is split.\nFinal line."; 
    // we add two characters at the start of each line "* " so lines can now 
    // be only 48 chars in length 
    description = addLinebreaks(description, 48); 
    String lines[] = description.split("\\r?\\n"); 
    ST descTemplate = templates.getInstanceOf("description"); 
    for (String line : lines) 
    { 
     descTemplate.add("lines", line); 
    } 
    System.out.println(descTemplate.render()); 
} 


// used to add line breaks if the length is greater than 50 
// From this SO question: http://stackoverflow.com/questions/7528045/large-string-split-into-lines-with-maximum-length-in-java 
public static String addLinebreaks(String input, int maxLineLength) { 
    StringTokenizer tok = new StringTokenizer(input, " "); 
    StringBuilder output = new StringBuilder(input.length()); 
    int lineLen = 0; 
    while (tok.hasMoreTokens()) { 
     String word = tok.nextToken()+" "; 

     if (lineLen + word.length() > maxLineLength) { 
      output.append("\n"); 
      lineLen = 0; 
     } 

     output.append(word); 
     lineLen += word.length(); 
    } 
    return output.toString(); 
} 

輸出I得到是:

* 
* This is a small description of the program, 
* with a line-width of 50 chars max, so the line 
* is split. 
* Final line. 
* 

它看起來有點不同於你的例子,但確實符合50個字符的限制。我想你可以玩它,直到它符合你的要求。