Introduction
FreeMarker is a template engine, which is a general tool based on templates and data to be changed and used to generate text
grammar
Basic instructions
插值表达式
${name}
注释
<#--<td>注释内容</td>-->
list command
<#if stus??>//判断某变量是否存在
<#list stus as stu>
<tr>
<td>${stu_index+1}</td>//序号
<td>${stu.name!''}</td>//若不存在则显示为空
<td>${stu.age}</td>
<td>${(stu.birthday?date)!''}</td>
<td>${(stu.bestFriend.name)!''}</td>
<td>${(stu.friends?size)!0}</td>
<td>
<#if stu.friends??>
<#list stu.friends as firend>
${firend.name!''}<br/>
</#list>
</#if>
</td>
</tr>
</#list>
</#if>
map command
第一种遍历
${stuMap['stu1'].name}<br/>
第二种遍历
${stuMap.stu1.name}<br/>
遍历键集[k]的[]不能省略
<#list stuMap?keys as k>
<tr>
<td>${k_index + 1}</td>//序号
<td>${stuMap[k].name}</td>
<td>${stuMap[k].age}</td>
<td >${stuMap[k].mondy}</td>
</tr>
</#list>
if instruction
<td <#if stu.name =='小强'>style="background:red;"</#if>>${stu.name}</td>
Built-in function
集合大小
${list?size}
防止数字三位分割
${number?c}
日期格式化
显示年月日: ${today?date}
显示时分秒:${today?time}
显示日期+时间:${today?datetime} <br>
自定义格式化: ${today?string("yyyy年MM月")}
字符串变为Java对象
<#assign text="{'bank':'工商银行','account':'1010120201920212'}" />
<#assign data=text?eval />
开户行:${data.bank} 账号:${data.account}
Perform static
private String generateHtml(String templateContent,Map model ){
//创建配置对象
Configuration configuration = new Configuration(Configuration.getVersion());
//创建模板加载器
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
stringTemplateLoader.putTemplate("template",templateContent);
//向configuration配置模板加载器
configuration.setTemplateLoader(stringTemplateLoader);
//获取模板
try {
Template template = configuration.getTemplate("template");
//调用api进行静态化
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
return content;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}