本文共 1703 字,大约阅读时间需要 5 分钟。
FreeMarker是一个基于java的免费开源的模板引擎,基于文本的模板输出工具,有着丰富的表达式,还可以自定义表达式。Freemarker可以将后端准备好的数据,通过Freemarker表达式在前端页面展示出来。在软件项目中常常用来生成HTML的 Web页面,可以基于模板生成输出文件,导出复杂样式的excel。
org.springframework.boot spring-boot-starter-freemarker
spring: freemarker: cache: false suffix: .ftl template-loader-path: classpath:/templates content-type: text/html; charset=utf-8 settings: number_format: 0 # 数字不进行千分位自动转换,比较大的数字会带有逗号,如1,000
在说方法前,先吐槽一下Freemarker比较恶心的地方,就是空错误,如果你页面表达式是null,就会报错,所以在使用的时候要先进行空判断,有时候页面报错就是因为这个。
1.获取元素值
<#if (msg)!=""> ${msg}
2.获取map中的值
${map["name"]}
3.foreach,循环输出list,先判断是否
<#if students ?? && students ?size gt 0> <#list students as student> ${student.name} ${student.age} ${student.sex}
4.逻辑判断,if…else方法,
字符串类型判断<#if type == 1> type=1 <#elseif type == 2> type=2
布尔值类型判断
<#if (booleanVal?string('yes', 'no'))=='yes'> 对 <#else> 错
多个值进行if判断
<#if flag=="1"> 1 <#elseif flag=="2"> 2 <#elseif flag=="3"> 3 <#else> 除了1、2、3之外
5.获取session中的值,如后端在session中保存userId,使用Freemarker
在session中保存userId的值request.getSession().setAttribute("userId",userId);
在页面使用freemarker表达式,为避免userId的值是空就会报错,所以要先判断一下
<#if Session["userId"]?exists> ${Session["userId"]}
6.Freemarker格式化时间
// 输出时间格式 2020-05-09 13:59:32${createTime?string('yyyy-MM-dd hh:mm:ss')}
7.使用include标签,引入其他页面
抽出公共页面代码,取名right.ftl,如下在需要引入该代码的页面中,使用include标签
<#include "right.ftl">
转载地址:http://btdpz.baihongyu.com/