# 简介

img

# 模板引擎技术对比

img

# 快速入门

  1. 创建freemarker-demo工程
  2. 引入相关依赖
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-freemarker</artifactId>
     </dependency>
    
  3. 编写yaml配置文件
    server:
      port: 8083
    spring:
      freemarker:
         #关闭缓存
         cache: false
         #设置模板文件的后缀
         suffix: .ftl
         #设置模板检查更新延迟时间, 设置为0为立即检查更新, 以方便我们测试
         settings:
           template_update_delay: 0
      application:
        name: test-freemarker
    
  4. 编写controller和模板文件 img

# Freemarker指令语法

# 基础语法种类

基础语法种类, 就是模板文件中,支持哪些语法.

  1. 注释, <#-- --,在其之间的内容会被freemarker忽略
    <#--我是一个freemarker注释-->
    
  2. 插值(Interpolation): 即${..}部分, freemarker会用真实的值代替${..}
    hello #{name}
    
  3. FTL指令: 和HTML标记类似, 名字前加#予以区分, Freemarker会解析标签中的表达式或者逻辑.
    <# >FTL指令</#>
    
  4. 文本, 仅文本信息,这些不是freemarker的注释,插值,FTL指令的内容会被freemarker忽略解析, 直接输入内容
    <#--freemarker中的普通文本-->
    我是一个普通文本
    

# 集合指令(List和Map)

掌握如何通过freemarker遍历list和map集合

# 遍历List

指令格式

<#list><#list>

例子

<#list stus as stu>
 <tr>
    <td>${stu_index + 1}</td>
    <td>${stu.name}</td>
    <td>${stu.age}</td>
    <td>${stu.money}</td>
 </tr>
</#list>

注意: ${x_index},可以用来得到循环的下标, 在stu侯曼加上_index,它的值是从0开始

# 遍历Map

img

    @GetMapping("/map")
    public String map(Model model){
        //1. 准备数据
        Student s1 = new Student("snake", "男", 21);
        Student s2 = new Student("saber", "女", 19);
        Student s3 = new Student("fox", "男", 20);
        //2. 封装成map
        HashMap<String, Student> stuMap = new HashMap<>();
        stuMap.put("stu1",s1);
        stuMap.put("stu2",s2);
        stuMap.put("stu3",s3);
        //3. 返回数据
        model.addAttribute("stuMap",stuMap);
        return "03-map";
    }
    <h1>
        方式1: 通过map['keyName'].属性名 来获取数据
    </h1>
    输出stu1的信息 <br>
    姓名: ${stuMap['stu1'].name} <br>
    年龄: ${stuMap['stu1'].age} <br>
    <hr>
    <h1>
        方式2: 通过map.keyName.属性名 来获取数据
    </h1>
    输出stu2的信息<br>
    姓名: ${stuMap.stu2.name} <br>
    年龄: ${stuMap.stu2.age} <br>

    <hr>
    <h1>遍历map中学生的信息</h1>
    <table>
        <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
        </tr>
        <#list stuMap?keys as key>
            <tr>
                <td>${key_index + 1}</td>
                <td>${stuMap[key].name}</td>
                <td>${stuMap[key].age}</td>
                <td>${stuMap[key].sex}</td>
            </tr>
        </#list>
    </table>

# 判断语句 if指令

当条件成立展示内容

<#if 表达式>
<#else>
</#if>

需求: 在list集合中判断姓名为小红的数据, 设置字体显示为红色 img

TIP

= 与 == 作用是相同的, 都是比较判断.

# 运算符

数学运算符 img 比较运算符 img 逻辑运算符 img

# 空值处理

如果语法中使用的某些变量不存在, 则会报错. img

# 内建函数

Freemarker给我们提供了一些函数供我们使用, 比如说之前,从map集合获取所有的key就是使用了内建函数keys.

内建函数语法:

变量?函数
  1. 获取集合大小
    ${集合变量?size}
    
  2. 日期格式化
    显示年月日: ${today?date}
    显示时分秒: ${today?time}
    显示日期+时间: ${today?datetime}
    自定义日期格式化: ${today?string("yyyy年MM月")}
    
  3. 内建函数c
    model.addAttribute("point",123456789);
    
    我们添加一个数字类型的变量到域中时, 使用${point}显示这个数字的值, 他会默认采用每三位使用逗号分隔. 如果不想显示未每三位分隔的数字, 可以使用c函数将数字型转为字符串输出.
    ${point?c}
    
  4. eval函数: 将json字符串转化为对象. 这里使用assign标签, 它的作用是定义一个变量
    <#assign text="{'username': '贝当•加那美', 'sex': '女'}" />
    <#assign data=text?eval />
    姓名: ${data.username} , 性别: ${data.sex}
    

# 生成静态html文件

在上面的Freemarker的使用,都是使用SpringMVC返回一个视图, 这次我们使用freemarker帮我们生成静态的html文件. img

# 使用api

package com.heima;

import com.heima.pojo.Student;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 使用Freemarker的API, 依据02-list模板, 生成静态的html文件
 */
@SpringBootTest(classes = FreemarkerApplication.class)
public class CrateStaticHtmlTest {
    //注意Configuration的包是:  import freemarker.template.Configuration;
    @Autowired
    private Configuration configuration;
    
    @Test
    public void make() throws IOException, TemplateException {
        //传入模板名, 会从Freemarker配置的模板目录下寻找
        Template template = configuration.getTemplate("02-list.ftl");
        /**
         * 生成静态文件的主要的API,
         * 第一个参数: 是模型数据, 可以是实体类, Map类型
         * 第二个参数: 是一个输出流
         */
        template.process(getModelData(),new FileWriter("D:/list.html"));
    }

    private Map<String,Object> getModelData(){
        HashMap<String, Object> data = new HashMap<>();
        //准备模型数据
        Student s1 = new Student("snake", "男", 21);
        Student s2 = new Student("saber", "女", 19);
        Student s3 = new Student("fox", "男", 20);
        //2. 封装成集合
        List<Student> list = Arrays.asList(s1, s2, s3);
        //3. 返回数据
        data.put("stus",list);
        return data;
    }
}
更新时间: 2024年5月26日星期日下午4点47分