StringTemplate4是轻量级模板引擎,Antlr 组织开发,主要用于java代码,网页,邮件,或其他格式化文本的生成,只有一个依赖项。
模板引擎都有语法,如果我们要使用,就必须掌握语法。这里是StringTemplate4 项目地址,本文不讲解语法,只是用一个简单的示例,展示StringTemplate4的功能。
使用版本:
在POM文件中引入项目依赖
<dependencies>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>ST4</artifactId>
</dependency>
</dependencies>
编写EMail模板文件email.stg,存放到resources目录下,文件内容如下:
email(order,separator) ::= <<
<! This is a comment
!>Hello, <if(order.customer.firstName)><order.customer.firstName><else>dear customer<endif>!
On <order.orderDate> we received the following order:
Shipping address:
<if(order.customer.firstName)><order.customer.firstName> <endif><order.customer.lastName>
<order.customer.address>
<order.items:{item|<item.amount>x <item.article.name> à <item.article.price; format="currency"> = <item.subTotal; format="currency">};separator="\n">
<if(!order.freeShipping)>plus shipping = <order.shippingCost; format="currency"><endif>
<separator>
Total = <order.total; format="currency">
Thank you for ordering!
>>
使用StringTemplate4格式化非常简单,如下:
STGroup group = new STGroupFile("email.stg");
ST st = group.getInstanceOf("email");
st.add("order", order);
st.add("separator", "----------------");
System.out.println(st.render());
其中 order 变量就是数据。格式化的Email内容输出到控制台。格式化结果如下:
Hello, Oliver!
On Fri Jan 28 14:35:02 CST 2011 we received the following order:
Shipping address:
Oliver Zeigermann
Gaußstraße 180
22765 Hamburg
GERMANY
1x How to become famous à 17.80 = 17.80
2x Cool stuff à 1.00 = 2.00
plus shipping = 3.00
----------------
Total = 22.80
Thank you for ordering!
如果我们需要Order(订单)中关于金钱的信息格式化输出,该如何操作?这个很简单,我们需要定义格式化金钱的类(BigDecimalRenderer.java):
public static class BigDecimalRenderer implements AttributeRenderer<BigDecimal> {
private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat(
"##,##0.00", DecimalFormatSymbols.getInstance(Locale.GERMANY));
private static final String EURO_CHARACTER = "\u20AC";
@Override
public String toString(BigDecimal value, String formatString, Locale locale) {
if (formatString.equals("currency")) {
NumberFormat numberFormat = DECIMAL_FORMAT;
String formatted = numberFormat.format(value) + " "
+ EURO_CHARACTER;
return formatted;
}
return value.toString();
}
}
然后注册实例即可,如下:
STGroup group = new STGroupFile("email.stg");
group.registerRenderer(Date.class, new DateRenderer());
group.registerRenderer(BigDecimal.class, new BigDecimalRenderer());
ST st = group.getInstanceOf("email");
st.add("order", order);
st.add("separator", "----------------");
System.out.println(st.render());
DateRenderer是日期格式化类,框架自带的。
本文的全部代码,可以在这里查看string-template4,感谢支持!