Freemark 初识

Freemark基础学习

1、freemark基础

1.1 基础语法种类
  1. 注释:<#-- 内容 -->

    <#--hello ${name}!-->
    
  2. 插值表达式:${变量}

  3. FTL:和HTMl类似,名字前加#予以区分,freemark会解析标签中的逻辑和表达式。

1.2 list指令
<#list stus as stu>
// 序号表示方法
${stu_index+1}
1.3 遍历map数据
// 方式一
${stuMap['stu1'].name}
${stuMap['stu1'].age}
// 方式二
${stuMap.stu1.name}
${stuMap.stu1.age}
// 遍历map
<#list stuMap?keys ad k>
姓名:${stuMap[k].name}
年龄:${stuMap[k].age}
1.4 if 指令
<td <#if stu.name == 'smilevers'>style="background: cornflowerblue;"</#if> >
1.5 逻辑表达式

支持常见的逻辑表达式

  • > :大于号,用gt代替,不然解析失败
  • >=:大于等于,用gte
  • < :小于,用lt
  • <=:小于等于,用lte

注意:= 和 != 可以用于字符串,数值和日期的比较,但是两边必须是相同的类型。其他运算符可以用于数字和日期的比较,但不能用于字符串。

1.6 空值处理
  • 空值:

    // ??来判断是否空值,一般在遍历之前判断
    <#if stus ??>
    </#if>
    
  • 缺省值:!

    // 表示:如果这个值存在就显示,不然就显示‘’字符串,类似三元表达式
    ${(stu.bestFriend.name)!''}
    
1.7 内建函数
  • 判断集合的大小

    ${集合名?szie}
    
  • 日期格式化

    // 显示年月日
    ${today?date}
    // 显示时分秒
    ${today?time}
    // 显示日期+时间
    ${today?datetime}
    // 自定义格式化
    ${today?string("yyyy年MM月")}
    
  • 内建函数c
    将数值型转成字符串

    ${number?c}
    
  • 将json字符串转成对象

    <#assign text="json字符串"/>
    <#assign data=text?eval>
    ${data.name}
    

2、freemark使用

2.1 添加依赖
<!--freemark依赖*-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.2 配置yml
// spring.data下
freemarker:
     cache: false  #关闭模板引擎
     settings:
       template_update_delay: 0  #检查模板更新延迟时间,设置为0立即检查,如果时间大于0 有缓存不方便测试
2.3 静态化流程

ftl文件 + 模板数据 => 静态文件

/**
 * 页面静态化演示
 * @Author: smile
 * @Date: 2020/2/24
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class FreemarkTest {
    
    /**
     * 模板文件 + 模板数据 => 静态文件string
     * @throws IOException
     * @throws TemplateException
     */
    @Test
    public void testGenerateHtml() throws IOException, TemplateException {
        // 获取freemark的配置类
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 获取classpath的路径
        String path = this.getClass().getResource("/").getPath();
        // 定义模板路径
        configuration.setDirectoryForTemplateLoading(new File(path+"/templates/"));
        // 获取模板对象
        Template template = configuration.getTemplate("test1.ftl");
        //定义数据模型
        Map map = this.getMap();
        // 静态化,模板对象转字符串
        String templateIntoString = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        System.out.println(templateIntoString);
        
        // 输出到硬盘,IOUtils 输入输出流工具(开发中这一步不一定需要)
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = IOUtils.toInputStream(templateIntoString, "utf-8");
            outputStream = new FileOutputStream(new File("D:/test1.html"));
            IOUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            inputStream.close();
            outputStream.close();
        }
    
    }
    
    /**
     * 模板文件string + 模板数据 => 静态文件string
     * @throws IOException
     * @throws TemplateException
     */
    @Test
    public void testGenerateHtmlToString() throws IOException, TemplateException {
        // 获取freemark的配置类
        Configuration configuration = new Configuration(Configuration.getVersion());
        String templateString = "<!DOCTYPE html>\n" +
                "<html>\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>hello world</title>\n" +
                "\n" +
                "</head>\n" +
                "<body>\n" +
                "\n" +
                "hello ${name}!\n" +
                "\n" +
                "</body>\n" +
                "</html>";
        // 使用模板加载器
        StringTemplateLoader templateLoader = new StringTemplateLoader();
        templateLoader.putTemplate("template", templateString);
        // 在配置类中设置模板加载器
        configuration.setTemplateLoader(templateLoader);
        //获取模板对象
        Template template = configuration.getTemplate("template", "utf-8");
        //定义数据模型
        Map map = this.getMap();
        // 静态化,模板对象转字符串
        String templateIntoString = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        System.out.println(templateIntoString);
        
        // 输出到硬盘,IOUtils 输入输出流工具(开发中这一步不一定需要)
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = IOUtils.toInputStream(templateIntoString, "utf-8");
            outputStream = new FileOutputStream(new File("D:/test2.html"));
            IOUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            inputStream.close();
            outputStream.close();
        }
    
    }
    // 模拟的模板数据,实际开发从数据库中查并保存到Map集合
    private Map getMap() {
        Map map = new HashMap();
        map.put("name", "smilevers");
        return map;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章