public class FreemarkerUtil {
/**
* 根据参数格式化字符串
*/
public static String format(String templateContent, Map<String, Object> param) {
Configuration cfg = new Configuration();
StringTemplateLoader stringLoader = new StringTemplateLoader();
stringLoader.putTemplate("myTemplate", templateContent);
cfg.setTemplateLoader(stringLoader);
try {
Template template = cfg.getTemplate("myTemplate", "utf-8");
StringWriter writer = new StringWriter();
try {
template.process(param, writer);
return writer.toString();
} catch (TemplateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
Map root = new HashMap();
root.put("name", "javaboy2012");
String templateContent = "欢迎:${name}";
String testIf = "<#if name??> ${name} </#if> ,你好";
System.out.println(FreemarkerUtil.format(templateContent, root));
System.out.println(FreemarkerUtil.format(testIf,root));
List<String> lists = new ArrayList<>();
lists.add("1:a");
lists.add("2:b");
lists.add("3:c");
root.put("lists",lists);
String tempList = "<#list lists as str>${str}</#list>";
System.out.println(FreemarkerUtil.format(tempList,root));
//Map集合
Map<String,String> map = new HashMap<>();
map.put("s1","panghl1");
map.put("s2","panghl2");
root.put("map",map);
String tempMap1 = "${map.s1} / ${map.s2}";
System.out.println(FreemarkerUtil.format(tempMap1, root));
String tempMap2 = "<#list map?keys as k>${map[k]}</#list>";
System.out.println(FreemarkerUtil.format(tempMap2,root));
//List<Map>集合
List<Map<String,String>> mapList = new ArrayList<>();
mapList.add(map);
root.put("mapList",mapList);
String tempMapList1 = "<#list mapList as ml>mapList: ${ml.s1} / ${ml.s2}</#list>";
System.out.println(FreemarkerUtil.format(tempMapList1,root));
String tempMapList2 = "<#list mapList as ml><#list ml?keys as k>mapList-->${ml[k]}</#list></#list>";
System.out.println(FreemarkerUtil.format(tempMapList2,root));
//获得当前迭代的索引 用lists示例
String tempIndex = "<#list lists as l>${l_index}</#list>";
System.out.println(FreemarkerUtil.format(tempIndex,root));
String tempTemplate = "\n" +
"<#assign x=\"${world}\" />\n" +
"${x}\n" +
" \n" +
"<#assign x>\n" +
" <#list [\"星期一\", \"星期二\", \"星期三\", \"星期四\", \"星期五\", \"星期六\", \"星期天\"] as n>\n" +
" ${n}\n" +
" </#list>\n" +
"</#assign>\n" +
"${x}";
root.put("world","hello panghl");
System.out.println(FreemarkerUtil.format(tempTemplate,root));
//日期模板
String tempDate = "${cur_date?date}";
root.put("cur_date", LocalDateTime.now());
System.out.println(FreemarkerUtil.format(tempDate,root));
}
}