SlideShare a Scribd company logo
1 of 17
Download to read offline
Thymeleaf
Introduction
2013.3 anthonychen
Thymeleaf 簡介

● Java 實現的 template engine
● 以 XML / XHTML/HTML5 為基礎
● 可以在非 web 的環境下運作
● 完全取代 JSP & JSTL
Thymeleaf 的優點

● HTML 5
● 對 Web art designer 友善
● 與 Spring MVC 無縫整合
● 豐富的 ecosystem
● 擴充性高的 dialect 架構
Ecosystem
●   Thymeleaf module for Play Framework 1.2
    http://www.playframework.com/modules/thymeleaf-1.0/home
●   Thymeleaf + Tiles 2
    https://github.com/thymeleaf/thymeleaf-extras-tiles2
●   Thymeleaf + Spring Security 3
    https://github.com/thymeleaf/thymeleaf-extras-springsecurity3
●   Thymeleaf eclipse IDE plugin
    https://sourceforge.net/projects/thymeleaf/files/thymeleaf-extras-eclipse-plugin
●   Thymeleaf + Spring MVC Maven archetype
    http://www.lordofthejars.com/2012/01/once-upon-time-and-long-ago-i-heard.html
●   Thymeleaf + Conditional Comments https://github.com/thymeleaf/thymeleaf-extras-
    conditionalcomments
Dialects
● Spring Dialect (build-in)
● Pages Dialect for Thymeleaf
● Layout Dialect
● Dandelion-DataTables Dialect
● Joda Time Dialect
● Apache Shiro Dialect
開始使用 Thymeleaf
1. 建立 html檔案並加上 HTML 5 及 thymeleaf xmlns宣告
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:th="http://www.thymeleaf.org">


2. Expression 語法 - OGNL or Spring Expression Language
●    存取變數 expressions
●    Selection expressions
●    文字處理與國際化 expressions
●    URL expressions
Thymeleaf Expressions (1)
● 存取變數 expressions
<td th:text="${#session.user.name}">Name</td>

<h1 th:text="${message}">Hello, world!</h1>

<tr th:each="user: ${userList}">

<legend th:if="${#lists.isEmpty(userList)}">No data</legend>

● Selection (asterisk) expressions
<form id="userForm" name="userForm" action="#" method="POST"
th:action="@{/user/save}" th:object="${user}">

<input type="text" id="inputAccount" placeholder="Account" th:
field="*{account}"/>
Thymeleaf Expressions (2)
● 文字處理與國際化 expressions
  <table>
    ...
    <th th:text="#{header.address.city}">...</th>
    <th th:text="#{header.address.country}">...</th>
    ...
  </table>

● URL expressions
  <div shiro:authenticated="false">
      <a href="#login" th:href="@{/login(id=${userId})}">
           Login
      </a>
  </ul>
Thymeleaf Helper Objects
#dates: 處理 java.util.Date 物件。包括建立、格式化、取得年/月/日...等
#calendars: 類似 #dates,用來處理 java.util.Calendar 物件
#numbers: 格式化或轉換數字格式
#strings: 處理字串物件
#objects: 單純處理物件的工具,例如 Null Safe 判斷
#bools: 判斷物件或陣列 boolean 值的工具.
#arrays:: 陣列工具
#lists: java.utils.List 工具
#sets: java.utils.Set 工具
#maps: java.utils.Map 工具
#aggregates: 處理 Collection 或 Array 聚合運算,例如計算陣列內容加總或平均
#messages : 處理國際化語言文字
Thymeleaf Helper Object 範例
日期格式化: ${#dates.format(date, ‘dd/MMM/yyyy HH:mm’)}
建立日期物件以取得現在時間: ${#dates.createNow()}
檢查字串 empty 或 null: ${#strings.isEmpty(name)}
其他字串處理: #strings.indexOf, #strings.substring, #strings.replace, #strings.
prepend, #strings.append, #strings.toUpperCase, #strings.toLowerCase,
#strings.trim, #strings.length, #strings.abbreviate
字串集合物件處理: #strings.listJoin, #strings.arrayJoin, #strings.setJoin, strings.
listSplit, strings.arraySplit, strings.setSplit
List 物件處理: ${#lists.size(list)}, ${#lists.isEmpty(list)}, ${#lists.contains(list,
element)}
聚合運算: ${#aggregates.sum(array), ${#aggregates.avg(array)}
國際化: ${#messages.msg(‘msgKey’)}, ${#messages.msg(‘msgKey’, param1,
param2)}
Template 運用
● Apache Tiles
  ○ https://github.com/thymeleaf/thymeleaf-extras-tiles2
● Thymol - th:include
  ○ http://sourceforge.net/u/jjbenson/wiki/thymol/
● Layout Dialect
  ○ https://github.com/ultraq/thymeleaf-layout-dialect
Thymeleaf + Spring MVC 3 (1)
   在 Spring configuration file 設定 Spring Standard Dialect
<!-- Thymeleaf template recolver -->
<bean id="templateResolver"
      class="org.thymeleaf.templateresolver.ServletContextTemplateResolver" >
    <property name="cacheable" value="false"/>
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".html"/>
    <property name="templateMode" value="HTML5"/>
    <property name="characterEncoding" value="UTF-8"/>
</bean>

<!-- Thymeleaf template engine -->
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine" >
    <property name="templateResolver" ref="templateResolver" />
    <property name="dialects" >
        <set>
            <bean class="org.thymeleaf.spring3.dialect.SpringStandardDialect" />
        </set>
    </property>
</bean>
Thymeleaf + Spring MVC 3 (2)
在 Spring configuration file 設定 View resolver
<!-- Thymeleaf view resolver -->
<bean id="viewResolver" class="org.thymeleaf.spring3.view.
ThymeleafViewResolver">
    <property name="templateEngine" ref="templateEngine"/>
    <property name="characterEncoding" value="UTF-8"/>
</bean>


如果你需要客製自己的 View bean
<bean name="main" class="org.thymeleaf.spring3.view.ThymeleafView" >
    <property name="staticVariables" >
        <map>
            <entry key="header" value="Hello" />
            <entry key="footer" value="Create by anthonychen" />
        </map>
    </property>
</bean>
擴充 Thymeleaf
 ● 建立 attribute 或 element processor (IProcessor Interface)

 ● 建立 dialect - 繼承 AbstractDialect

 ● 將 dialect 加入 thymeleaf 設定


SAY HELLO! EXTENDING THYMELEAF IN 5 MINUTES
HTTP://WWW.THYMELEAF.ORG/SAYHELLOEXTENDINGTHYMELEAF5MINUTES.HTML


SAY HELLO AGAIN! EXTENDING THYMELEAF EVEN MORE IN ANOTHER 5 MINUTES
HTTP://WWW.THYMELEAF.
ORG/SAYHELLOAGAINEXTENDINGTHYMELEAFEVENMORE5MINUTES.HTML
參考資源
●   Getting started
     ○   Getting started with the Standard dialects in 5 minutes
         http://www.thymeleaf.org/standarddialect5minutes.html
     ○   Standard URL Syntax
         http://www.thymeleaf.org/standardurlsyntax.html
●   Documentation http://www.thymeleaf.org/documentation.html
     ○   Using Thymeleaf
     ○   Thymeleaf + Spring 3
     ○   Extending Thymeleaf
●   User forum http://forum.thymeleaf.org/
●   Other resource
     ○   Rich HTML email in Spring with Thymeleaf (http://www.thymeleaf.org/springmail.html)
     ○   Using Thymeleaf with Spring MVC (http://blog.zenika.com/index.php?
         post/2013/01/21/using-thymeleaf-with-spring-mvc)
你還可以...
● Thymeleaf + Ajax
  JQuery, Dojo, Spring JavaScript (part of Spring WebFlow)
● Thymeleaf + Responsive CSS Framework
  Bootstraps, Foundation, Skeleton
● Thymeleaf + JRebel
● 寫個 dialect 吧
   ○ JSP taglib --> Thymeleaf dialect
   ○ JQuery plugin --> Thymeleaf dialect
Thank You!

More Related Content

What's hot

Pourquoi WordPress n’est pas un CMS
Pourquoi WordPress n’est pas un CMSPourquoi WordPress n’est pas un CMS
Pourquoi WordPress n’est pas un CMS
Thomas Gasc
 
Ch. 9 jsp standard tag library
Ch. 9 jsp standard tag libraryCh. 9 jsp standard tag library
Ch. 9 jsp standard tag library
Manolis Vavalis
 

What's hot (20)

PHP for hacks
PHP for hacksPHP for hacks
PHP for hacks
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
 
Php converted pdf
Php converted pdfPhp converted pdf
Php converted pdf
 
Ppt php
Ppt phpPpt php
Ppt php
 
Pourquoi WordPress n’est pas un CMS
Pourquoi WordPress n’est pas un CMSPourquoi WordPress n’est pas un CMS
Pourquoi WordPress n’est pas un CMS
 
Php
PhpPhp
Php
 
Current state-of-php
Current state-of-phpCurrent state-of-php
Current state-of-php
 
Using PHP
Using PHPUsing PHP
Using PHP
 
Introduction To Lamp
Introduction To LampIntroduction To Lamp
Introduction To Lamp
 
Being a jsp
Being a jsp     Being a jsp
Being a jsp
 
symfony & jQuery (phpDay)
symfony & jQuery (phpDay)symfony & jQuery (phpDay)
symfony & jQuery (phpDay)
 
Php
PhpPhp
Php
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
Ch. 8 script free pages
Ch. 8 script free pagesCh. 8 script free pages
Ch. 8 script free pages
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJS
 
Laravel the right way
Laravel   the right wayLaravel   the right way
Laravel the right way
 
Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016
 
Ch. 9 jsp standard tag library
Ch. 9 jsp standard tag libraryCh. 9 jsp standard tag library
Ch. 9 jsp standard tag library
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 
Cake PHP 3 Presentaion
Cake PHP 3 PresentaionCake PHP 3 Presentaion
Cake PHP 3 Presentaion
 

Viewers also liked

Shootout! template engines on the jvm
Shootout! template engines on the jvmShootout! template engines on the jvm
Shootout! template engines on the jvm
NLJUG
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 

Viewers also liked (20)

Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
Shootout! template engines on the jvm
Shootout! template engines on the jvmShootout! template engines on the jvm
Shootout! template engines on the jvm
 
Thymeleaf, will it blend?
Thymeleaf, will it blend?Thymeleaf, will it blend?
Thymeleaf, will it blend?
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Shootout! Template engines for the JVM
Shootout! Template engines for the JVMShootout! Template engines for the JVM
Shootout! Template engines for the JVM
 
Website design configuration
Website design configurationWebsite design configuration
Website design configuration
 
App Design + Layout
App Design + LayoutApp Design + Layout
App Design + Layout
 
Thymeleafのすすめ
ThymeleafのすすめThymeleafのすすめ
Thymeleafのすすめ
 
Spring User Group Thymeleaf 08-21-2013
Spring User Group Thymeleaf 08-21-2013Spring User Group Thymeleaf 08-21-2013
Spring User Group Thymeleaf 08-21-2013
 
DSpace UI Prototype Challenge: Spring Boot + Thymeleaf
DSpace UI Prototype Challenge: Spring Boot + ThymeleafDSpace UI Prototype Challenge: Spring Boot + Thymeleaf
DSpace UI Prototype Challenge: Spring Boot + Thymeleaf
 
Java™ in Web 2.0
Java™ in Web 2.0Java™ in Web 2.0
Java™ in Web 2.0
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and Thymeleaf
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
OAuth2 and Spring Security
OAuth2 and Spring SecurityOAuth2 and Spring Security
OAuth2 and Spring Security
 
REST with Spring Boot #jqfk
REST with Spring Boot #jqfkREST with Spring Boot #jqfk
REST with Spring Boot #jqfk
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 

Similar to Thymeleaf Introduction

Twig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHPTwig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHP
Fabien Potencier
 
Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress
Maurizio Pelizzone
 

Similar to Thymeleaf Introduction (20)

19servlets
19servlets19servlets
19servlets
 
Servlets
ServletsServlets
Servlets
 
Servlets Java Slides & Presentation
Servlets Java Slides & Presentation Servlets Java Slides & Presentation
Servlets Java Slides & Presentation
 
The JavaFX Ecosystem
The JavaFX EcosystemThe JavaFX Ecosystem
The JavaFX Ecosystem
 
Twig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHPTwig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHP
 
Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress
 
vJUG - The JavaFX Ecosystem
vJUG - The JavaFX EcosystemvJUG - The JavaFX Ecosystem
vJUG - The JavaFX Ecosystem
 
Core data intermediate Workshop at NSSpain 2013
Core data intermediate Workshop at NSSpain 2013Core data intermediate Workshop at NSSpain 2013
Core data intermediate Workshop at NSSpain 2013
 
Performance Tuning Your Puppet Infrastructure - PuppetConf 2014
Performance Tuning Your Puppet Infrastructure - PuppetConf 2014Performance Tuning Your Puppet Infrastructure - PuppetConf 2014
Performance Tuning Your Puppet Infrastructure - PuppetConf 2014
 
Twig: Friendly Curly Braces Invade Your Templates!
Twig: Friendly Curly Braces Invade Your Templates!Twig: Friendly Curly Braces Invade Your Templates!
Twig: Friendly Curly Braces Invade Your Templates!
 
.NET @ apache.org
 .NET @ apache.org .NET @ apache.org
.NET @ apache.org
 
Lightweight web frameworks
Lightweight web frameworksLightweight web frameworks
Lightweight web frameworks
 
The JavaFX Ecosystem
The JavaFX EcosystemThe JavaFX Ecosystem
The JavaFX Ecosystem
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
The JavaFX Ecosystem
The JavaFX EcosystemThe JavaFX Ecosystem
The JavaFX Ecosystem
 
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
 
Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!
 
Play Framework
Play FrameworkPlay Framework
Play Framework
 
Puppet at Bazaarvoice
Puppet at BazaarvoicePuppet at Bazaarvoice
Puppet at Bazaarvoice
 
Apache Zeppelin and Helium @ApacheCon 2017 may, FL
Apache Zeppelin and Helium  @ApacheCon 2017 may, FLApache Zeppelin and Helium  @ApacheCon 2017 may, FL
Apache Zeppelin and Helium @ApacheCon 2017 may, FL
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Thymeleaf Introduction

  • 2. Thymeleaf 簡介 ● Java 實現的 template engine ● 以 XML / XHTML/HTML5 為基礎 ● 可以在非 web 的環境下運作 ● 完全取代 JSP & JSTL
  • 3. Thymeleaf 的優點 ● HTML 5 ● 對 Web art designer 友善 ● 與 Spring MVC 無縫整合 ● 豐富的 ecosystem ● 擴充性高的 dialect 架構
  • 4. Ecosystem ● Thymeleaf module for Play Framework 1.2 http://www.playframework.com/modules/thymeleaf-1.0/home ● Thymeleaf + Tiles 2 https://github.com/thymeleaf/thymeleaf-extras-tiles2 ● Thymeleaf + Spring Security 3 https://github.com/thymeleaf/thymeleaf-extras-springsecurity3 ● Thymeleaf eclipse IDE plugin https://sourceforge.net/projects/thymeleaf/files/thymeleaf-extras-eclipse-plugin ● Thymeleaf + Spring MVC Maven archetype http://www.lordofthejars.com/2012/01/once-upon-time-and-long-ago-i-heard.html ● Thymeleaf + Conditional Comments https://github.com/thymeleaf/thymeleaf-extras- conditionalcomments
  • 5. Dialects ● Spring Dialect (build-in) ● Pages Dialect for Thymeleaf ● Layout Dialect ● Dandelion-DataTables Dialect ● Joda Time Dialect ● Apache Shiro Dialect
  • 6. 開始使用 Thymeleaf 1. 建立 html檔案並加上 HTML 5 及 thymeleaf xmlns宣告 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> 2. Expression 語法 - OGNL or Spring Expression Language ● 存取變數 expressions ● Selection expressions ● 文字處理與國際化 expressions ● URL expressions
  • 7. Thymeleaf Expressions (1) ● 存取變數 expressions <td th:text="${#session.user.name}">Name</td> <h1 th:text="${message}">Hello, world!</h1> <tr th:each="user: ${userList}"> <legend th:if="${#lists.isEmpty(userList)}">No data</legend> ● Selection (asterisk) expressions <form id="userForm" name="userForm" action="#" method="POST" th:action="@{/user/save}" th:object="${user}"> <input type="text" id="inputAccount" placeholder="Account" th: field="*{account}"/>
  • 8. Thymeleaf Expressions (2) ● 文字處理與國際化 expressions <table> ... <th th:text="#{header.address.city}">...</th> <th th:text="#{header.address.country}">...</th> ... </table> ● URL expressions <div shiro:authenticated="false"> <a href="#login" th:href="@{/login(id=${userId})}"> Login </a> </ul>
  • 9. Thymeleaf Helper Objects #dates: 處理 java.util.Date 物件。包括建立、格式化、取得年/月/日...等 #calendars: 類似 #dates,用來處理 java.util.Calendar 物件 #numbers: 格式化或轉換數字格式 #strings: 處理字串物件 #objects: 單純處理物件的工具,例如 Null Safe 判斷 #bools: 判斷物件或陣列 boolean 值的工具. #arrays:: 陣列工具 #lists: java.utils.List 工具 #sets: java.utils.Set 工具 #maps: java.utils.Map 工具 #aggregates: 處理 Collection 或 Array 聚合運算,例如計算陣列內容加總或平均 #messages : 處理國際化語言文字
  • 10. Thymeleaf Helper Object 範例 日期格式化: ${#dates.format(date, ‘dd/MMM/yyyy HH:mm’)} 建立日期物件以取得現在時間: ${#dates.createNow()} 檢查字串 empty 或 null: ${#strings.isEmpty(name)} 其他字串處理: #strings.indexOf, #strings.substring, #strings.replace, #strings. prepend, #strings.append, #strings.toUpperCase, #strings.toLowerCase, #strings.trim, #strings.length, #strings.abbreviate 字串集合物件處理: #strings.listJoin, #strings.arrayJoin, #strings.setJoin, strings. listSplit, strings.arraySplit, strings.setSplit List 物件處理: ${#lists.size(list)}, ${#lists.isEmpty(list)}, ${#lists.contains(list, element)} 聚合運算: ${#aggregates.sum(array), ${#aggregates.avg(array)} 國際化: ${#messages.msg(‘msgKey’)}, ${#messages.msg(‘msgKey’, param1, param2)}
  • 11. Template 運用 ● Apache Tiles ○ https://github.com/thymeleaf/thymeleaf-extras-tiles2 ● Thymol - th:include ○ http://sourceforge.net/u/jjbenson/wiki/thymol/ ● Layout Dialect ○ https://github.com/ultraq/thymeleaf-layout-dialect
  • 12. Thymeleaf + Spring MVC 3 (1) 在 Spring configuration file 設定 Spring Standard Dialect <!-- Thymeleaf template recolver --> <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver" > <property name="cacheable" value="false"/> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".html"/> <property name="templateMode" value="HTML5"/> <property name="characterEncoding" value="UTF-8"/> </bean> <!-- Thymeleaf template engine --> <bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine" > <property name="templateResolver" ref="templateResolver" /> <property name="dialects" > <set> <bean class="org.thymeleaf.spring3.dialect.SpringStandardDialect" /> </set> </property> </bean>
  • 13. Thymeleaf + Spring MVC 3 (2) 在 Spring configuration file 設定 View resolver <!-- Thymeleaf view resolver --> <bean id="viewResolver" class="org.thymeleaf.spring3.view. ThymeleafViewResolver"> <property name="templateEngine" ref="templateEngine"/> <property name="characterEncoding" value="UTF-8"/> </bean> 如果你需要客製自己的 View bean <bean name="main" class="org.thymeleaf.spring3.view.ThymeleafView" > <property name="staticVariables" > <map> <entry key="header" value="Hello" /> <entry key="footer" value="Create by anthonychen" /> </map> </property> </bean>
  • 14. 擴充 Thymeleaf ● 建立 attribute 或 element processor (IProcessor Interface) ● 建立 dialect - 繼承 AbstractDialect ● 將 dialect 加入 thymeleaf 設定 SAY HELLO! EXTENDING THYMELEAF IN 5 MINUTES HTTP://WWW.THYMELEAF.ORG/SAYHELLOEXTENDINGTHYMELEAF5MINUTES.HTML SAY HELLO AGAIN! EXTENDING THYMELEAF EVEN MORE IN ANOTHER 5 MINUTES HTTP://WWW.THYMELEAF. ORG/SAYHELLOAGAINEXTENDINGTHYMELEAFEVENMORE5MINUTES.HTML
  • 15. 參考資源 ● Getting started ○ Getting started with the Standard dialects in 5 minutes http://www.thymeleaf.org/standarddialect5minutes.html ○ Standard URL Syntax http://www.thymeleaf.org/standardurlsyntax.html ● Documentation http://www.thymeleaf.org/documentation.html ○ Using Thymeleaf ○ Thymeleaf + Spring 3 ○ Extending Thymeleaf ● User forum http://forum.thymeleaf.org/ ● Other resource ○ Rich HTML email in Spring with Thymeleaf (http://www.thymeleaf.org/springmail.html) ○ Using Thymeleaf with Spring MVC (http://blog.zenika.com/index.php? post/2013/01/21/using-thymeleaf-with-spring-mvc)
  • 16. 你還可以... ● Thymeleaf + Ajax JQuery, Dojo, Spring JavaScript (part of Spring WebFlow) ● Thymeleaf + Responsive CSS Framework Bootstraps, Foundation, Skeleton ● Thymeleaf + JRebel ● 寫個 dialect 吧 ○ JSP taglib --> Thymeleaf dialect ○ JQuery plugin --> Thymeleaf dialect