标签
模板
字数
1122 字
阅读时间
5 分钟
一、概述
FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java 等。
二、整合示例
2.1 与springboot整合
依赖
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐starter‐freemarker</artifactId>
</dependency>配置
yml
server:
port: 8088 #服务端口
spring:
application:
name: test‐freemarker #指定服务名
freemarker:
cache: false #关闭模板缓存,方便测试
settings:
template_update_delay: 0 #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便 进行模板测试2.2 与ssm整合
依赖
xml
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>配置
xml
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
<property name="defaultEncoding" value="UTF-8" />
</bean>使用
java
@Controller
public class HtmlGenController {
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@RequestMapping("/genhtml")
@ResponseBody
public String genHtml()throws Exception {
// 1、从spring容器中获得FreeMarkerConfigurer对象。
// 2、从FreeMarkerConfigurer对象中获得Configuration对象。
Configuration configuration = freeMarkerConfigurer.getConfiguration();
//设置字符集
configuration.setDefaultEncoding("utf‐8");
// 3、使用Configuration对象获得Template对象。
Template template = configuration.getTemplate("hello.ftl");
// 4、创建数据集
Map dataModel = new HashMap<>();
dataModel.put("hello", "1000");
// 5、创建输出文件的Writer对象。
Writer out = new FileWriter(new File("D:/temp/term197/out/spring-freemarker.html"));
// 6、调用模板对象的process方法,生成文件。
template.process(dataModel, out);
// 7、关闭流。
out.close();
return "OK";
}
}java
//基于模板字符串生成静态化文件
@Test
public void testGenerateHtmlByString() throws IOException, TemplateException {
//创建配置类
Configuration configuration=new Configuration(Configuration.getVersion());
//模板内容,这里测试时使用简单的字符串作为模板
String templateString="" + "<html>\n" + " <head></head>\n"
+ " <body>\n" + " 名称:${name}\n" + " </body>\n"
+ "</html>";
//模板加载器
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
stringTemplateLoader.putTemplate("template",templateString);
configuration.setTemplateLoader(stringTemplateLoader);
//得到模板
Template template = configuration.getTemplate("template","utf‐8");
//数据模型
Map<String,Object> map = new HashMap<>();
map.put("name","黑马程序员");
//静态化
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
//静态化内容
System.out.println(content);
InputStream inputStream = IOUtils.toInputStream(content);
//输出文件
FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.html"));
IOUtils.copy(inputStream, fileOutputStream);
}三、语法
3.1 获取数据
html
<!-- 简单类型,使用EL表达式 -->
<label>姓名:</label>${student.name}<br>
<!-- 数组集合类型 -->
<#list persons as p>
${p.id}/${p.name}
获取当前选代的索引:${p.index}集合大小${集合名?size}
</#list>3.2 逻辑处理
html
<!-- 判断 -->
<#if 判断条件>
<#else>
</#if>3.3 函数
html
<!-- 日期格式化 -->
date
${cur_time?date}
datetime
${cur_time?datetime}
time
${cur_time?time}
自定义格式
${cur_time?string("yyyy-MM-dd HH:mm:ss")}
<!-- 处理null值 -->
null 变 空串
${val!} ${val!""}
为Null时给默认值
${val!“我是默认值"}
<#if curdate ??>
当前日期:${curdate?string("yyyy/MM/dd HH:mm:ss")}
<#else>
curdate属性为null
</#if>
<!-- 导入 将另一个页面引入 -->
<#include "/include/head.html">
<!-- 内建函数c -->
<!-- 将point代表的数字变为每三位分隔的形式 -->
${point?c}
<!-- 将json字符串转换为对象 -->
<#assign text="{'bank':'工商银行','account':'10101920201920212'}" />
<#assign data=text?eval />
开户行:${data.bank} 账号:${data.account}3.4 运算符
html
1. 算数运算符 FreeMarker表达式中完全支持算术运算,FreeMarker支持的算术运算符包括:+, - , * , / , %
2. 逻辑 运算符 逻辑运算符有如下几个: 逻辑与:&& 逻辑或:|| 逻辑非:! 逻辑运算符只能作用于布尔值,否则将产生错误
3. 比较运算符 表达式中支持的比较运算符有如下几个:
1. =或者==:判断两个值是否相等.
2. !=:判断两个值是否不等.
3. 或者gt:判断左边值是否大于右边值
4. >=或者gte:判断左边值是否大于等于右边值
5. <或者lt:判断左边值是否小于右 边值
6. <=或者lte:判断左边值是否小于等于右边值
注意: =和!=可以用于字符串,数值和日期来比较是否相等,但=和!=两边必须是相同类型的值,否则会产生错误,而且 FreeMarker是精确比较,"x","x ","X"是不等的.其它的运行符可以作用于数字和日期,但不能作用于字符串,大部分的时 候,使用gt等字母运算符代替>会有更好的效果,因为 FreeMarker会把>解释成FTL标签的结束字符,当然,也可以使用括 号来避免这种情况,如:<#if (x>y)>