本文是【模闆中指派】demo
java
/**
* 模闆中指派
*/
@Test
public void test1() throws IOException {
//1 加載配置
Properties properties = new Properties();
properties.load(Test.class.getClassLoader().getResourceAsStream("velocity.properties"));
Velocity.init(properties);
//2 建立上下文對象
VelocityContext context = new VelocityContext();
//3 指派
context.put("name", "趙先森");
context.put("date", new Date());
context.put("dateformat", new DateUtils());
context.put("dateTime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
//4選擇模闆
Template template = Velocity.getTemplate("./src/test/resources/template/test1.vm");
//5 合并模闆和資料并輸出
StringWriter sw = new StringWriter();
template.merge(context, sw);
sw.flush();
log.info("-----------------------------start------------------------------------");
log.info(sw.toString());
log.info("-----------------------------end------------------------------------");
}
模闆 test1.vm
#set($ints=["第一個","第二個","第三個"])
$ints
----------------華麗的分隔線--------------------------
#set($name="趙先森")
$name
#set($hh="我的名字是"+$name)
$hh
#set($aa = $hh.substring(2,$hh.length()))
截取後的字段是:$aa
----------------華麗的分隔線--------------------------
#set($condition=true)
#set($condition=false)
$condition
#*
#if($condition)
成立
#stop
#else
不成立
#stop
#end
*#
----------------華麗的分隔線--------------------------
date : $date
format1 : $dateformat.format($date)
format2 : $dateformat.format($date,"yyyy-MM-dd")
dateTime : $dateTime