Proj. THUIoTFuzz Java工具-stringtemplate4

Hello, World

import org.stringtemplate.v4.*;
...
ST hello = new ST("Hello, <name>");
hello.add("name", "World");
System.out.println(hello.render());

Groups of templates

如果一个文件夹中有多个templates,比如有decl.st和init.st。
那么可以用以下代码来加载

STGroup group = new STGroupDir("/tmp");
ST st = group.getInstanceOf("decl");
st.add("type", "int");
st.add("name", "x");
st.add("value", 0);
String result = st.render(); // yields "int x = 0;"

同个文件夹底下的.st文件也可以相互调用,比如

// file /tmp/init.st
init(v) ::= "<if(v)> = <v><endif>"
// file /tmp/decl.st
<type> <name><init(value)>;

当然更简单的是直接把两个templates放入一个.stg(string template group)文件中

// file /tmp/test.stg
decl(type, name, value) ::= "<type> <name><init(value)>;"
init(v) ::= "<if(v)> = <v><endif>"

model fields

ST st = new ST("<b>$u.id$</b>: $u.name$", '$', '$');
st.add("u", new User(999, "parrt"));
String result = st.render(); // "<b>999</b>: parrt"

data aggregation

ST st = new ST("<items:{it|<it.id>: <it.lastName>, <it.firstName>
}>");
st.addAggr("items.{ firstName ,lastName, id }", "Ter", "Parr", 99); // add() uses varargs
st.addAggr("items.{firstName, lastName ,id}", "Tom", "Burns", 34);
String expecting =
        "99: Parr, Ter
"+
        "34: Burns, Tom
"+

Applying templates to attributes

如果我们调用add()两次,分别设置name属性为"parrt"和"tombu",那么<name>将被渲染为"parrttombu"。
可以添加separator,则<name; separator=", ">的渲染结果"parrt, tombu"
还可以为每个attribute都渲染模板,比如:

test(name) ::= "<name:bracket(); separator=", ">"
bracket(x) ::= "[<x>]"

匿名模板

test(name) ::= "<name:{x | [<x>]}; separator=", ">"
原文地址:https://www.cnblogs.com/xuesu/p/14695583.html