0%

springBoot整合freemarker

文章字数:276,阅读全文大约需要1分钟

freemarker是一款模板引擎,适用于mvc框架

引入依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

配置信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
spring.freemarker.allow-request-override=false
# 关闭缓存
spring.freemarker.cache=false
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
#文件后缀名
#spring.freemarker.suffix=.ftl
#spring.freemarker.template-loader-path=classpath:/templates/ #comma-separated list
#spring.freemarker.view-names= # whitelist of view names that can be resolved

使用

  • 基本使用

    1
    <h1>Hello , ${name}</h1>
  • Controller.java*

    1
    2
    3
    4
    5
    public ModelAndView view(){
    ModelAndView mv = new ModelAndView("hello");
    mv.addObject("name","xxx");
    return mv;
    }
  • 循环

    1
    2
    3
    <#list studentList as student>
    ${student.id}/${studnet.name}
    </#list>
    1
    2

    下标

    <#list studentList as student>
    ${student_index}
    </#list>

  • 判断

    1
    2
    3
    <#if student_index % 2 == 0>
    <#else>
    </#if>
  • 日期格式化

    1
    2
    3
    4
    日期:${date?date}
    时间:${date?time}
    日期时间:${date?datetime}
    自定义格式:${date?string("yyyyMM/dd HH:mm:ss")}
  • null处理

    1
    2
    3
    4
    5
    ${name!"默认..."}
    判断
    <#if name??>
    <#else>
    </#if>
  • 包含其他

    1
    <#include "hello.ftl"/>

宏定义

就是定义一个代码片段,在其它地方可以复用
####不带参数

  1. 定义
    1
    2
    3
    <#macro greet>  
    <font size="+2">Hello Joe!</font>
    </#macro>
  2. 复用
    1
    2
    3
    <@greet></@greet>  
    或者
    <@greet/>

    带参使用

  • 定义
    1
    2
    3
    4
    5
    <#macro header title="默认文字" keywords="默认文字" description="默认文字"> 
    <title>${title}</title>
    <meta name="keywords" content="${keywords}" />
    <meta name="description" content="${description}" />
    </#macro>
  • 使用
    1
    2
    3
    <!-- 引入上面的定义文件 -->
    <#include "/include/public.ftl">
    <@header title="公司简介" keywords="公司简介2" description="公司简介3">

实例

  1. 重复生成固定数量的元素
1
2
3
4
5
6
7
8
9
10
<!-- 定义一个1到28的数组 -->
<#assign months=1..28/>
<select name="" id="">
<!-- 遍历数组 -->
<#list months as month>
<option value="${month}">${month}</option>
</#list>
</select>
<!-- 其它生成方式 -->
<#assign months=[1,2,3,4,5,6,7,8,9,0]/>