东东
发布于 2024-12-19 / 5 阅读 / 0 评论 / 0 点赞

FreeMarker模板引擎

基础

先看文档

什么是 FreeMarker? - FreeMarker 中文官方参考手册

通过使用模板(在模板中写好动态参数)以及具体的动态参数,从而生成想要的文件。

这种方式就像现在网页的渲染一样,前端是模板,通过向后端请求数据,然后将具体的动态数据填充到模板中,从而渲染出完整页面。

组成

模板文件由以下几部分组成

1、文本

文本内容会在生成文件时按照原样输出

2、插值

插值就是需要替换的动态数据

3、FTL指令

标签语法,用来实现各种功能,例如循环、判断等

4、注释

语法

插值

表达式:${100 + money}

判断

<#if user == "test">
  我是test
<#else>
  我是test1
</#if>

默认值

${user!"用户为空"}

循环

<#list users as user>
  ${user}
</#list>

也就是定义一个代码块,在使用的时候一整个拿过来复用

<#macro card userName>     
---------    
${userName}
---------
</#macro>



<@card userName="test"/>

实战测试

引入Maven坐标

<!-- https://freemarker.apache.org/index.html -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.32</version>
</dependency>

如果是springboot,可以引入start

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

创建一个全局配置对象

// new 出 Configuration 对象,参数为 FreeMarker 版本号
Configuration configuration = new Configuration(Configuration.VERSION_2_3_32);

// 指定模板文件所在的路径
configuration.setDirectoryForTemplateLoading(new File("src/main/resources/templates"));

// 设置模板文件使用的字符集
configuration.setDefaultEncoding("utf-8");

准备加载模板

// 创建模板对象,加载指定模板
Template template = configuration.getTemplate("test.html.ftl");

生成文件

Writer out = new FileWriter("myweb.html");
template.process(dataModel, out);

// 生成文件后别忘了关闭哦
out.close();