Freemarker详解(二)

这一篇续上篇, 让我们继续来学习一下,Freemarker,话不多说,煌sir带你上干货~~

 

一. 其他指令

1.运算符

  • 算数运算符:FreeMarker表达式中完全支持算术运算

算数运算符

+

-

*

/

%

 

  • 逻辑运算符

逻辑运算符

描述

&&

逻辑与

||

逻辑或

!

逻辑非

 

  • 比较运算符

比较运算符

描述

==

判断两个值是否相等

!=

判断两个值是否不等

>或者gt

判断左边值是否大于右边值

>=或者gte

判断左边值是否大于等于右边值

<或者lt

判断左边值是否小于右边值

<=或者lte

判断左边值是否小于等于右边值

 

  • 注意:>、>=、<、<= 可能出现与预期结果不一致的情况,建议使用等效的字母

实例

<#if num > 60 >
    num大于60
</#if>

 

  • 如果num为100,num表示条件成立,输出结果:
  • 60 > num 大于 60

 

  • 建议编写方式

<#if num gt 60 >
    num大于60
</#if>

 

 

2. 空值处理

  • 判断某变量是否存在使用 “??”

变量?? ,如果不为空返回true,如果为空返回false

Controller:

@GetMapping("/if")
public String _if(Model model) {
    //设置数据
    model.addAttribute("token", 1234);
    model.addAttribute("token2", "5678");
    return "if";
}

if.ftl:

<#--空值处理-->
<#--不为空处理-->
<#if token??>
    token不为空 <br/>
</#if>

<#--为空处理-->
<#if !token3??>
    token3为空 <br/>
</#if>

<#--默认值-->
${token3!'3的默认值'}<br/>

测试:

 

 

 

3.内建函数

内建函数语法格式: 变量+?+函数名称

//和到某个集合的大小
${集合名?size}

//显示年月日: 
        ${日期?date}
//显示时分秒:
        ${日期?time}
//显示日期+时间:
        ${日期?datetime} <br>
//自定义格式化:  
${日期?string("yyyy年MM月")}

//不想显示为每三位分隔的数字
        ${数字变量?c}

//将json字符串转成对象
        text?eval

 

Controller:

@GetMapping("/method")
public String method(Model model) {
    //集合
    ArrayList<String> list = new ArrayList<>();
    list.add("abc");
    list.add("1234");
    model.addAttribute("list", list);
   //时间
    model.addAttribute("birthday", new Date());
    // 整形
    model.addAttribute("num", 12345678);
    //JSON数据
   model.addAttribute("userJSON", JSONObject.toJSONString(new User("aaa", "bbb", 33)));

    //设置页面
    return "method";
}

 

method.ftl:

显示集合大小: ${list?size} <br/>

显示年月日:${birthday?date} <br/>
显示时分秒: ${birthday?time} <br/>
显示日期+时间: ${birthday?datetime} <br/>
自定义格式化: ${birthday?string("yyyy年MM月")}<br/>
${birthday?string("yyyy/MM/dd HH:mm:ss:SSS")}<br/>

整形数据:<br/>
默认显示:${num} <br/>
格式化:${num?c} <br/>

JSON数据:<br/>
字符串:${userJSON} <br/>
<#assign user=userJSON?eval />
对象输出:${user.username} <br/>

测试:

 

 

二.静态化

1.模板文件静态化

定义模板文件,使用freemarker静态化程序生成html文件

  • 步骤1:修改pom文件,添加IO依赖

  • 我上篇最开始的依赖已提供(可无需再添加)

https://my.oschina.net/ithuang/blog/4324855

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
</dependency>

 

步骤二:创建 src/test/resources文件夹 ,并设置其为资源文件夹

设置方式一:

 

设置方式二:

 

 

步骤三:创建测试模板文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
${name}
</body>
</html>

 

步骤四:编写测试类

@Test
public void tset1() throws Exception {
    //根据模板生成html
    // 1.核心配置类
    Configuration configuration = new Configuration(Configuration.getVersion());
    // 2.设置模板文件夹
  // 2.1.获得类路径 /test_freemarker/target/test-classes/
    String classpath = this.getClass().getResource("/").getPath();
    System.out.println(classpath);
   // 2.2.静态目录
   // File templateDir = new File(classpath);  //在resource根目录下创,不用额外路径
    File templateDir = new File(classpath,"/templates/");
     // 2.3.给配置类设置操作目录
   configuration.setDirectoryForTemplateLoading(templateDir);
    // 3.设置编码
    configuration.setDefaultEncoding("UTF-8");

    // 4.获得具体模板 test.ftl
    Template template = configuration.getTemplate("test.ftl");
    //5.准备数据
    HashMap<String, String> map = new HashMap<>();
    map.put("name","ce999");

    // 6.静态haul生产,字符串内容
    String s = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
    System.out.println(s);
  // 7.将 "字符串"写入文件汇总
    File file = new File(templateDir,"test.html");
    FileUtils.writeStringToFile(file,s);
}

 

步骤五:测试结果

 

 

2.​​​​​​​模板字符串静态化

定义模板字符串,使用freemarker静态化程序生成html文件

@Test
public void testString() throws Exception {
    // 1.定义字符串模板-后期数据从数据库查询
   String stringTemplate="<!DOCTYPE html>\n" +
           "<html lang=\"en\">\n" +
           "<head>\n" +
           "    <meta charset=\"UTF-8\">\n" +
           "    <title>Title</title>\n" +
           "</head>\n" +
           "<body>\n" +
           "${name}\n" +
           "</body>\n" +
           "</html>";
    // 2.声明模板加载器
    StringTemplateLoader templateLoader = new StringTemplateLoader();
    templateLoader.putTemplate("myTemplate",stringTemplate);
    // 3.核心配置类,需要使用模板加载器,最终将字符串加载成模板
    Configuration configuration = new Configuration(Configuration.getVersion());
   configuration.setTemplateLoader(templateLoader);
    // 4.获得指定命名模板
    Template myTemplate = configuration.getTemplate("myTemplate", "UTF-8");

    // 5.准备数据
    HashMap<String, String> map = new HashMap<>();
    map.put("name","字符串填充666");
    // 6.静态化
    String str = FreeMarkerTemplateUtils.processTemplateIntoString(myTemplate, map);
    // 7.IO 写入
    String path = this.getClass().getResource("/templates").getPath();
    File file = new File(path, "test1.html");
    FileUtils.writeStringToFile(file,str);
}

 

同理:测试结果

 

 

 

看完恭喜你,又知道了一点点!!!

你知道的越多,不知道的越多! 

~感谢志同道合的你阅读,  你的支持是我学习的最大动力 ! 加油 ,陌生人一起努力,共勉!!

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