看起来您想要在这里做几件事——将描述放在以星号开头的行上,但如果有换行符或长度大于 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 个字符的限制。我想你可以玩弄它,直到它符合你的要求。