stringtemplate java_StringTemplate语法

阳航
2023-12-01

1 变量替换

public static void fun1() {

StringTemplate st = new StringTemplate(

"对象变量替换 姓名:$KeyList.Name$, 年龄:$KeyList.Age$ ");

HashMap ht = new HashMap();

ht.put("Name", "李四");

ht.put("Age", "35");

st.setAttribute("KeyList", ht);

System.out.print(st.toString());

}

2 自定义集合替换

public static void fun2() {

StringTemplate st = new StringTemplate(

"自定义集合替换 $List:{姓名:$it.Name$ 年龄:$it.Age$}$");

st.setAttribute("List.{Name,Age}", "王二", "29");

System.out.print(st.toString());

}

3 对象变量替换

定义类

private static class User {

String name;

String age;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getAge() {

return age;

}

public void setAge(String age) {

this.age = age;

}

}

public static void fun3() {

User us = new User();

us.name = "张三";

us.age = "23";

List uss = new ArrayList();

uss.add(us);

uss.add(us);

uss.add(us);

uss.add(us);

uss.add(us);

StringTemplate st = new StringTemplate(

"

class=black>

$it.name$},{

class=red>

$it.age$};separator=\"\n\"$");

st.setAttribute("Item", uss);

System.out.print(st.toString());

}

交叉替换

public static void fun4() {

User us = new User();

us.name = "张三";

us.age = "23";

List uss = new ArrayList();

uss.add(us);

uss.add(us);

uss.add(us);

uss.add(us);

uss.add(us);

StringTemplateGroup sg = new StringTemplateGroup("GroupTest");

sg.defineTemplate("RowRed",

"

$it.Name$$it.Age$\n");

sg.defineTemplate("Rowblack",

"

$it.Name$$it.Age$\n");

StringTemplate st = sg.defineTemplate("List",

"

");

st.setAttribute("Item", uss);

System.out.print(st.toString());

}

4 条件判断

public static void fun5() {

StringTemplate st = new StringTemplate(

"当前用户登陆状态: $if(IsAdmin)$ 用户登陆成功! $else$ 用户没有登陆! $endif$");

st.setAttribute("IsAdmin", true);

System.out.print(st.toString());

}

5 sql语句实现

theQuery.st内容

SELECT $column; separator=","$ FROM $table$;

public static void fun6() {

// 一个sql语句的实现

StringTemplateGroup group = new StringTemplateGroup("myGroup", "c:/");

StringTemplate query = group.getInstanceOf("theQuery");

query.setAttribute("column", "name");

query.setAttribute("column", "email");

query.setAttribute("table", "User");

System.out.print(query.toString());

}

6 使用AttributeRenderer

private static class DateRenderer implements AttributeRenderer {

public String toString(Object o) {

SimpleDateFormat f = new SimpleDateFormat("yyyy.MM.dd");

return f.format(((Calendar) o).getTime());

}

}

public static void fun7() {

StringTemplate st = new StringTemplate("date: ",

AngleBracketTemplateLexer.class);

st.setAttribute("created", new GregorianCalendar(2005, 07 - 1, 05));

st.registerRenderer(GregorianCalendar.class, new DateRenderer());

String result = st.toString();

System.out.print(result.toString());

}

posted on 2009-11-14 13:40 BlakeSu 阅读(842) 评论(0)  编辑  收藏

 类似资料: