如何生成多行注释

时间:2014-09-12 13:53:02

标签: stringtemplate stringtemplate-4

在stringtemplate-4中,如何生成多行注释?例如,模板是这样的(注释的开头和结尾都在其他模板中):

test(DESCRIPTION) ::= <<
*
* <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.
*

1 个答案:

答案 0 :(得分:0)

看起来你想在这里做一些事情 - 把描述放在一行开头 用星号,但如果换行或长度大于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();
}

我得到的输出是:

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

看起来与您的示例略有不同,但确实符合50个字符限制。我想你可以玩它,直到它符合你的要求。