Thymeleaf(Java模板引擎)


一、概念

1、Thymeleaf是Web和獨立環境的開源的Java模板引擎,能夠處理HTML,XML,JavaScript,CSS甚至純文本;
2、Thymeleaf可以在Web(基於Servlet)和非Web環境中工作,它更適合在基於MVC的Web應用程序的視圖層提供XHTML / HTML5 ,但它甚至可以在脫機環境中處理任何XML文件。它提供完整的Spring Framework集成
3、在Web應用程序中,Thymeleaf旨在成為JSP的完全替代品,並實現自然模板的概念:模板文件,可以直接在瀏覽器中打開,仍然可以正確顯示為網頁;

二、環境配置

1、如果用maven需要下載thymeleaf-2.1.4.RELEASE.jar(http://www.thymeleaf.org/download.html ),然后在pom里添加依賴
2、整合spring的需要下載thymeleaf-spring4-2.1.4.RELEASE.jar(http://www.thymeleaf.org/download.html ),然后添加依賴
3、servlet配置

<!-- Scans the classpath of this application for @Components to deploy as beans -->
       <context:component-scan base-package="com.test.thymeleaf.controller" />

       <!-- Configures the @Controller programming model -->
       <mvc:annotation-driven />

        <!--Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
        <!--springMVC+jsp的跳轉頁面配置-->
       <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
              <!--<property name="prefix" value="/WEB-INF/views/" />-->
              <!--<property name="suffix" value=".jsp" />-->
       <!--</bean>-->

       <!--springMVC+thymeleaf的跳轉頁面配置-->
       <bean id="templateResolver"
          class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
         <property name="prefix" value="/WEB-INF/views/" />
         <property name="suffix" value=".html" />
         <property name="templateMode" value="HTML5" />
       </bean>

       <bean id="templateEngine"
           class="org.thymeleaf.spring4.SpringTemplateEngine">
          <property name="templateResolver" ref="templateResolver" />
       </bean>

       <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
         <property name="templateEngine" ref="templateEngine" />
       </bean>
View Code

4、html
引用命名空間: <html xmlns:th="http://www.thymeleaf.org">
可避免編輯器出現html驗證錯誤,但是不加對Thymeleaf的功能也沒有影響;

三、語法

1、表達式

    ${name}        可用值表達式,變量取值(變量名name又后台傳入);
    *{name}        所有可用值表達式,從可用值中查找name,如果有上下文,比如上層(即父標簽)是object,則查object中的name屬性(th:object="")。
    #{nmae}        消息表達式,國際化時使用,也可以使用內置的對象,比如date格式化數據;(消息通常指:外部文本抽取模板代碼片段到模板文件外面, 使外部文本可以存在另一個文件中)
    @{name}        鏈接表達式,用來配合link,src,href使用的
    ~{name}        片段表達式,用來引入公共部分代碼片段,並進行傳值操作使用;

示例:
    服務器變量 map.put("msgutext","<b>1111</b>");
    html內容:

    <div th:utext="${msgutext}"></div>        顯示結果為粗體的1111
    <div th:text="${msgutext}"></div>         顯示結果為:<b>1111</b>

2、運算符

    數學:+,-,*,/,%
    比較:gt,lt,ge,le,eq,ne
    邏輯:and,or,not,!
    條件:? :  ,?: (默認值,例:    value ?: defaultvalue,條件語句也可以不只要?號,相當於沒有else)
    其他:+(字符串連接),_(禁止轉義),||(替換,內容可包含非參數內容,如:<a href="" th:href="@{|xx${value}|}"
   

3、支持的html5操作

(基本所有屬性都支持了,只是在前邊加了一個th:)
常用th標簽

th:id          替換id
th:text        替換標簽內文本
th:utext       html文本替換,可使文本內的標簽生效
th:object      替換對象
th:value       屬性賦值
th:with        變量賦值運算,例<div th:with="isEven=${prodStat.count}%2==0"></div>
th:style       替換樣式
th:onclick     點擊事件
th:each        屬性賦值
th:if          條件判斷,例:<a th:if="${userId == collect.userId}" > 
th:unless      條件判斷
th:href        鏈接地址
th:switch      switch選擇,和th:case一起使用
th:fragmetn    布局標簽
th:include    
th:replace
th:selected
th:src
th:inline
th:action
th:remove
th:attr        設置任意標簽屬性,一般較少用到,因為所有的屬性都有對應的th:

一個標簽內多個th屬性生效的優先順序:
include,each,if/unless/switch/case,with,attr/attrprepend/attrappend,value/href,src ,etc,text/utext,fragment,remove

4、內嵌數據類型

(內置於Contex中,可通過#直接訪問)

dates            java.util.Date的功能方法,${#dates.createNow()}
calendars        java.util.Calendar
numbers          數字
strings          字符串
objects          objects功能類
bools            布爾值
arrays           數組功能類
lists            list功能類
sets             集合功能類            
maps             字典功能類

內置基本對象(可通過#訪問)
ctx,vars,locale,request,response,session,servletContext

 

5、遍歷

<tr th:each="data:${getdata}">
    <td th:text="${data.id}"></td>
    <td th:text="${data.name}"></td>
    ...
</tr>

大部分java集合類型都可以用此來遍歷

同時th:each還提供了一個變量可以保存迭代狀態
狀態包含以下屬性:

    index      索引,從0開始
    count      計數,從1開始
    size      集合內元素總數
    current    當前迭代對象
    even/odd   奇偶數個,bool類型
    first      是否是第一個,bool類型
    last       是否是最后一個,bool類型

示例:

 <li th:each="emp, status: ${employees}" th:class="${status.odd} ? 'odd': 'even'"> 
    <span class="list" th:text="${emp.name}"></span>
    <span class="list" th:text="${emp.gender == 1} ? '男': '女'"></span> 
    <span class="list" th:text="${{emp.birthday}}"></span> 
    <span class="list status" th:text="|index: ${status.index}; count: ${status.count}; size: ${status.size}; first: ${status.first}|"></span> </li>
</li>
<!--如果沒有指定第二個參數的名字,有默認的以參數名+Stat為名字,如上沒有指定status則可以使用empStat提取上邊參數-->

 

6、條件(if,switch)

示例:

1)if
<tr th:each="test:${test}">
    <td th:if="${test.Score} gt 0 and ${test.Score} lt 60"></td>
    <td th:if="${test.Score} ge 60 and ${test.Score} le 70"></td>
    ...
</tr>

2)if unless

<tr th:each="test:${test}">
    <td th:if="${test.Score} gt 0 and ${test.Score} lt 60">不及格</td>
    <td th:unless="${test.Score} gt 0 and ${test.Score} lt 60">及格</td>
</tr>

3)switch

    <tr th:each="test:${test}">
        <td th:switch="${test.male}">
            <span th:case="1"></span>
            <span th:case="2"></span>
            <span th:case="*">未知</span>
        </td>
    </tr>

 

7、其他

1)外圍包裹th:block標簽:主要用於在代碼外部加一層條件,而不用多寫一個div

2)日期格式化:

<td th:text="${#dates.format(content.createDate,'yyyy-MM-dd HH:mm:ss')}"></td>

3)字符串長度截取:

<td th:if="${#strings.length(content.title) gt 5 } "  th:text="${#strings.substring(content.title,0,5) + '…'}"></td>

4)下拉選擇:

 <select name="subId" id="subId" lay-verify="" >
    <option value="">請選擇</option>
    <option th:each="channelsub:${subchannels}" th:selected="${channelsub.id == subId}"   th:value="${channelsub.id}" th:text="${channelsub.name}"></option>
 </select>

5)傳值到js

 <script th:inline="javascript">
        var size= [[${test.size()}]];
</script>

6)傳值到css

<style th:inline="css">
.[[${classname}]] {
text-align: [[${align}]];
}
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM