1. 程式人生 > >SpringBoot整合Freemarker模板引擎

SpringBoot整合Freemarker模板引擎

1、引入Maven依賴

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

2、yml配置屬性

spring:
  freemarker:
    suffix: .html  #字尾名,預設是.ftl
    content-type: text/html
    enabled: true
    cache:
false #快取配置 template-loader-path: classpath:/templates/ #模板載入路徑 按需配置 charset: UTF-8 #編碼格式 request-context-attribute: request #請求,類似jsp中的內建物件

request-context-attribute: request,這個屬性可以設定freemarker請求物件,其實就是JSP中的內建物件,

設定這個的好處就是我們可以在模版頁面中通過${request.contextPath}等方法,直接獲取需要的內容。

如果是前臺頁面模版引擎的方式,存在多個目錄,我們可能會在路徑設定的時候出現很多問題,相對路徑和絕對路徑分不清了,所以可以使用這個物件直接使用絕對路徑:

可以先設定一個全域性變數,方便使用,然後直接使用:

<#assign basPath=request.contextPath >
<script src="${basPath}/bootstrap3/js/jquery-1.11.2.min.js"></script>
<script src="${basPath}/bootstrap3/js/bootstrap.min.js"></script>    
....

<img src="${basPath}/images/user_icon.png"/>

3、模板常用語法

設定變數:<#assign a=10 >

引入其他檔案 : <#include "foreground/common/nav.html">

值的獲取:

​ 字面量:普通的值(數值、字串、布林…): ${str}

​ 物件:${dog.name}

​ map: ${map.key}

迴圈:

<#list dogList as dog>
    ${dog.name}    獲取當前索引====${dog_index}
</#list>

判斷:

<#if expression>
</#if>
<#if (a == 1) || (b == 3) >
<#else>
</#if>

空值判斷:

1、使用!指定預設值
$(name!"張三")
2、使用??判斷是否存在,存在返回true,不存在返回false
<#if name??>
    Welcome ${name}!
</#if> 

日期:

內建函式用來指定日期變數中的哪些部分被使用:

  • date:僅日期部分,沒有一天當中的時間部分。
  • time:僅一天當中的時間部分,沒有日期部分。
  • datetime:日期和時間都在
<!--時間格式  -->
${cur_time?date}
${cur_time?datetime}
${cur_time?time}
${cur_time?string("yyyy-MM-dd HH:mm:ss")}