【问题标题】:how to generate multi-line comment如何生成多行注释
【发布时间】:2014-09-12 13:53:01
【问题描述】:

在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.
*

【问题讨论】:

    标签: stringtemplate stringtemplate-4


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2012-07-05
      • 1970-01-01
      • 2013-08-01
      • 2012-04-24
      • 1970-01-01
      • 2019-07-11
      • 2015-05-29
      • 2021-12-04
      相关资源
      最近更新 更多