HashMap t2root = new HashMap<String, String>();
t2root.put("user", "RenSanNing");
${user}, Welcome!
3、输出一个列表
Map<String, Object> t3root = new HashMap<String, Object>();
List<Food> menu = new ArrayList<Food>();
menu.add(new Food("iText in Action", 98));
menu.add(new Food("iBATIS in Action", 118));
menu.add(new Food("Lucene in Action", 69));
t3root.put("menu", menu);
<#list menu as food>
${food.name} ${food.price?string.currency}
</#list>
<1>if, else, elseif:
<#if x == 1>
x is 1
<#elseif x == 2>
x is 2
<#elseif x == 3>
x is 3
<#elseif x == 4>
x is 4
<#else>
x is not 1 nor 2 nor 3 nor 4
</#if>
<2>switch, case, default, break:
<#switch y>
<#case "small">
This will be processed if it is small
<#break>
<#case "medium">
This will be processed if it is medium
<#break>
<#case "large">
This will be processed if it is large
<#break>
<#default>
This will be processed if it is neither
</#switch>
<3>list, break:
<#assign seq = ["winter", "spring", "summer", "autumn"]>
<#list seq as x>
${x_index + 1}. ${x}<#if x_has_next>,</#if>
</#list>
5、自定义函数
<#function fact n>
<#if n == 0>
<#return 1 />
<#else>
<#return fact(n - 1) * n />
</#if>
</#function>
<#list 0..10 as i>
${i}! => ${fact(i)}
</#list>
6、定义变量
<#-- 1、本地变量 -->[BR]
<#function partg n lst>
<#local ans = []>
<#list lst as x>
<#if (x >= n)>
<#local ans = ans + [x]>
</#if>
</#list>
<#return ans>
</#function>
<#assign ls = [10, 2, 4, 5, 8, 1, 3]>
<#list partg(4, ls) as x>${x} </#list>
<#-- 2、变量域测试 -->[BR]
<#macro test>
03. ${x}
<#global x = "global2">
04. ${x}
<#assign x = "assign2">
05. ${x}
<#local x = "local1">
06. ${x}
<#list ["循环1"] as x>
07. ${x}
<#local x = "local2">
08. ${x}
<#assign x = "assign3">
09. ${x}
</#list>
10. ${x}
</#macro>
<#global x = "global1" />
01. ${x}
<#assign x = "assign1" />
02. ${x}
<@test />
11. ${x}
public class SystemDateDirective implements TemplateDirectiveModel {
public void execute(Environment env, Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body) throws TemplateException, IOException {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
env.getOut().append(sdf.format(cal.getTime()));
}
}
public class TextCutDirective implements TemplateDirectiveModel {
public static final String PARAM_S = "s";
public static final String PARAM_LEN = "len";
public static final String PARAM_APPEND = "append";
@SuppressWarnings("unchecked")
public void execute(Environment env, Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body) throws TemplateException, IOException {
String s = getString(PARAM_S, params);
Integer len = getInt(PARAM_LEN, params);
String append = getString(PARAM_APPEND, params);
if (s != null) {
Writer out = env.getOut();
if (len != null) {
out.append(textCut(s, len, append));
} else {
out.append(s);
}
}
}
....
Map<String, Object> t10root = new HashMap<String, Object>();
t10root.put("systemdate", new SystemDateDirective());
t10root.put("text_cut", new TextCutDirective());