1.avg看到很多Freeemarker文档里面有avg:${avg(3,9,12)},还以为是默认就有的。后来才发现需要写代码传个avg方法变量。
public class AvgFroFreemarker implements TemplateMethodModel{ public Object exec(List arguments) throws TemplateModelException { double total=0.0; for(int i=0;i<arguments.size();i++){ //这边不做复杂判断(如字母。。) total+=Double.parseDouble(arguments.get(i).toString()); } return total/arguments.size(); } } public class XX{ public static void main(String args[]){ Configuration freemarkerCfg = new Configuration(); Template template=freemarkerCfg.getTemplate("Hello.ftl"); HashMap root = new HashMap(); root.put("avg", new AvgFroFreemarker()); StringWriter writer = new StringWriter(); template.process(root, writer); } } 用法: .ftl文件 avg:${avg(3,9,12)}
2.globals<#global x = "global_X" > <#list ["list_X"] as x> list:${x} global:${.globals.x} <#assign x = "global_X2"> <#-- replace the plain var, hiding does not mater here --> ${x} </#list> ${x}